Calculate supporting forces of an simply supported beam
I'd like to know if thorwables are good practice to handle semantic errors and if one should always use "getters" and "setters" or if it is ok to access fields in data model objects directly (the load Class).
How do you judge the readibility. Any tips/ hints?
This Class creates a beam:
/**
* A beam.
*
* @author Berthold
*
*/
import java.util.ArrayList;
import java.util.List;
public class Beam {
private double lengthOfBeam_m;
private List<Bearing> support;
private int numberOfBearings;
private List<Load> stress;
/*
* Create a beam
*/
public Beam(double lengthOfBeam_m) {
this.lengthOfBeam_m = lengthOfBeam_m;
support = new ArrayList<Bearing>();
numberOfBearings = 0;
stress = new ArrayList<Load>();
}
/*
* Add load
*/
public void addLoad(Load load) {
stress.add(load);
}
/*
* Add bearing
*/
public void addBearing(Bearing bearing) {
support.add(bearing);
}
/*
* Check if load/ bearing is inside length of beam
*/
public boolean isInsideOfBeamLength(double distanceFromLeftEndOfBeam_m) {
if (distanceFromLeftEndOfBeam_m >= 0 && distanceFromLeftEndOfBeam_m <= lengthOfBeam_m)
return true;
else
return false;
}
/*
* Getters
*/
public Load getLoad(int atIndex) {
return stress.get(atIndex);
}
public double getLength() {
return lengthOfBeam_m;
}
public int getNumberOfLoads() {
return stress.size();
}
public int getNumberOfBearings() {
return numberOfBearings;
}
public Bearing getBearing(int bearingIndexFromLeftEndOfBeam) {
return support.get(bearingIndexFromLeftEndOfBeam);
}
}
This class adds a bearing:
/*
* A Bearing
*/
public class Bearing {
private double distanceFromLeftEndOfBeam_m;
Bearing(double distanceFromLeftEndOfBeam_m) {
this.distanceFromLeftEndOfBeam_m = distanceFromLeftEndOfBeam_m;
}
public double getDistanceFromLeftEndOfBeam_m() {
return distanceFromLeftEndOfBeam_m;
}
}
Load:
/**
* Load
*
* Load acting downwards (-) Load acting upwards (+)
*
* @author Berthold
*
*/
public class Load {
private double force_N;
private double distanceFromLeftEndOfBeam_m;
private double lengthOfLineLoad_m;
/*
* Create a single force or a line load.
*/
public Load(double force_N, double distanceFromLeftEndOfBeam_m, double lengthOfLineLoad_m) {
this.force_N = force_N;
this.distanceFromLeftEndOfBeam_m = distanceFromLeftEndOfBeam_m;
this.lengthOfLineLoad_m = lengthOfLineLoad_m;
}
/*
* Getters
*/
public double getForce_N() {
return force_N;
}
public double getDistanceFromLeftEndOfBeam_m() {
return distanceFromLeftEndOfBeam_m;
}
public double getLengthOfLineLoad_m() {
return lengthOfLineLoad_m;
}
}
This class claculates the beams supporting forces:
/**
* Solves a simply supported beam with single and/ or line loads.
*
* Beam has a statically determined support configuration.
* Bearings may be placed arbitrary inside length of beam.
*
* Solver has to check for valid initial conditions.
* If any of the expected initial conditions are not met (e.g. bearing not inside beam length) result is set to 0
* and number of errors is increased. Calling class must deal with errors accordingly.
*
* Force, leading sign: (+) Force acts upwards (-) Force acts downwards.
* Torque, leading sing (+) Clockwise (-) Anti- clockwise.
*
* Result: Resulting forces at the bearings can point up or downwards.
* A negative result means that the force points in the opposite direction of the
* acting force. So, (-) means "upwards" regarding the result.
*
*
*
* F1 F2 Fn
* | | |
* -------0--------------------0--------------
* A A
* (F_Left) (F_Right)
*
* |---------- l -------|
*
*
* |
* |-l1---|
* |
* |-------------------l2------|
*
* |x1|
* |
* |--------x2----|
* |
* |----------------xn---------------|
*
*
* Solver calculates from left to right by solving the following equation:
* TorqueSumAtRightBearing=0=F_Leftxl-F1x(l2-x1)-F2x(l2-x2)-....-Fn(l2-xn)
*
* Resulting force at right bearing is calculated by solving this equation:
* SummOfVerticalForces=0=F_Left-F1-F2-....-Fn+F_Right
*
* @author Berthold
*
*/
public class Solve {
public static Result getResults(Beam beam) {
/*
* Init
*/
Result result = new Result();
int errorCount = 0;
double spaceBetweenBearings_m = 0;
double torqueSum = 0;
double loadSum = 0;
Load load;
/*
* Get and check bearings
*/
Bearing leftBearing = beam.getBearing(0);
Bearing rightBearing = beam.getBearing(1);
if (beam.isInsideOfBeamLength(leftBearing.getDistanceFromLeftEndOfBeam_m())
&& beam.isInsideOfBeamLength(rightBearing.getDistanceFromLeftEndOfBeam_m())) {
spaceBetweenBearings_m = Math
.abs(leftBearing.getDistanceFromLeftEndOfBeam_m() - rightBearing.getDistanceFromLeftEndOfBeam_m());
} else
result.setErrorCount(++errorCount);
/*
* Get and check loads, calculate resultant forces at left and right
* bearing
*/
for (int i = 0; i <= beam.getNumberOfLoads() - 1; i++) {
load = beam.getLoad(i);
if (beam.isInsideOfBeamLength(load.getDistanceFromLeftEndOfBeam_m()) && beam
.isInsideOfBeamLength(load.getDistanceFromLeftEndOfBeam_m() + load.getLengthOfLineLoad_m())) {
if (load.getLengthOfLineLoad_m() == 0) {
// Load is a single load
loadSum = loadSum + load.getForce_N();
torqueSum = torqueSum + load.getForce_N()
* (rightBearing.getDistanceFromLeftEndOfBeam_m() - load.getDistanceFromLeftEndOfBeam_m());
} else {
// Load is line load
double resultandForce_N = load.getForce_N() * load.getLengthOfLineLoad_m();
double distanceOfResultandForceFromLeftEndOfbeam_m = (load.getDistanceFromLeftEndOfBeam_m())
+ load.getLengthOfLineLoad_m() / 2;
loadSum = loadSum + resultandForce_N;
torqueSum = torqueSum + resultandForce_N * (rightBearing.getDistanceFromLeftEndOfBeam_m()
- distanceOfResultandForceFromLeftEndOfbeam_m);
}
} else
result.setErrorCount(++errorCount);
}
if (errorCount == 0) {
result.setResultingForceAtLeftBearingBearing_N(-1 * torqueSum / spaceBetweenBearings_m);
result.setResultingForceAtRightBearing_N(-1 * loadSum - result.getResultingForceAtLeftBearing_N());
}
return result;
}
}
The Result:
/**
* Result
*
* TODO: Implement error description....
*
* @author Berthold
*
*/
public class Result {
private int errorCount;
private double resultingForceAtLeftBearing_N, resultingForceAtRightBearing_N;
public int getErrorCount() {
return errorCount;
}
public void setErrorCount(int errorCount) {
this.errorCount = errorCount;
}
public double getResultingForceAtRightBearing_N() {
return resultingForceAtRightBearing_N;
}
public void setResultingForceAtRightBearing_N(double resultingForceAtRightBearing_N) {
this.resultingForceAtRightBearing_N = resultingForceAtRightBearing_N;
}
public double getResultingForceAtLeftBearing_N() {
return resultingForceAtLeftBearing_N;
}
public void setResultingForceAtLeftBearingBearing_N(double resultingForceAtLeftBearing_N) {
this.resultingForceAtLeftBearing_N = resultingForceAtLeftBearing_N;
}
}
Sample application:
/**
* A simple driver
*
* Create a beam, add loads, solve.....
*
*/
public class MainBeamCalculator {
public static void main(String args) {
Beam myBeam = new Beam(12);
myBeam.addBearing(new Bearing(0));
myBeam.addBearing(new Bearing(9));
myBeam.addLoad(new Load(-10, 3, 0));
myBeam.addLoad(new Load(-5, 5, 0));
Result result = Solve.getResults(myBeam);
if (result.getErrorCount() == 0) {
System.out.println("Beam. Loads:" + myBeam.getNumberOfLoads());
System.out.println("Left bearing:" + result.getResultingForceAtLeftBearing_N() + " N. Right bearing:"
+ result.getResultingForceAtRightBearing_N() + " N.");
} else
System.out.println("Errors:" + result.getErrorCount());
}
}
java physics
New contributor
add a comment |
I'd like to know if thorwables are good practice to handle semantic errors and if one should always use "getters" and "setters" or if it is ok to access fields in data model objects directly (the load Class).
How do you judge the readibility. Any tips/ hints?
This Class creates a beam:
/**
* A beam.
*
* @author Berthold
*
*/
import java.util.ArrayList;
import java.util.List;
public class Beam {
private double lengthOfBeam_m;
private List<Bearing> support;
private int numberOfBearings;
private List<Load> stress;
/*
* Create a beam
*/
public Beam(double lengthOfBeam_m) {
this.lengthOfBeam_m = lengthOfBeam_m;
support = new ArrayList<Bearing>();
numberOfBearings = 0;
stress = new ArrayList<Load>();
}
/*
* Add load
*/
public void addLoad(Load load) {
stress.add(load);
}
/*
* Add bearing
*/
public void addBearing(Bearing bearing) {
support.add(bearing);
}
/*
* Check if load/ bearing is inside length of beam
*/
public boolean isInsideOfBeamLength(double distanceFromLeftEndOfBeam_m) {
if (distanceFromLeftEndOfBeam_m >= 0 && distanceFromLeftEndOfBeam_m <= lengthOfBeam_m)
return true;
else
return false;
}
/*
* Getters
*/
public Load getLoad(int atIndex) {
return stress.get(atIndex);
}
public double getLength() {
return lengthOfBeam_m;
}
public int getNumberOfLoads() {
return stress.size();
}
public int getNumberOfBearings() {
return numberOfBearings;
}
public Bearing getBearing(int bearingIndexFromLeftEndOfBeam) {
return support.get(bearingIndexFromLeftEndOfBeam);
}
}
This class adds a bearing:
/*
* A Bearing
*/
public class Bearing {
private double distanceFromLeftEndOfBeam_m;
Bearing(double distanceFromLeftEndOfBeam_m) {
this.distanceFromLeftEndOfBeam_m = distanceFromLeftEndOfBeam_m;
}
public double getDistanceFromLeftEndOfBeam_m() {
return distanceFromLeftEndOfBeam_m;
}
}
Load:
/**
* Load
*
* Load acting downwards (-) Load acting upwards (+)
*
* @author Berthold
*
*/
public class Load {
private double force_N;
private double distanceFromLeftEndOfBeam_m;
private double lengthOfLineLoad_m;
/*
* Create a single force or a line load.
*/
public Load(double force_N, double distanceFromLeftEndOfBeam_m, double lengthOfLineLoad_m) {
this.force_N = force_N;
this.distanceFromLeftEndOfBeam_m = distanceFromLeftEndOfBeam_m;
this.lengthOfLineLoad_m = lengthOfLineLoad_m;
}
/*
* Getters
*/
public double getForce_N() {
return force_N;
}
public double getDistanceFromLeftEndOfBeam_m() {
return distanceFromLeftEndOfBeam_m;
}
public double getLengthOfLineLoad_m() {
return lengthOfLineLoad_m;
}
}
This class claculates the beams supporting forces:
/**
* Solves a simply supported beam with single and/ or line loads.
*
* Beam has a statically determined support configuration.
* Bearings may be placed arbitrary inside length of beam.
*
* Solver has to check for valid initial conditions.
* If any of the expected initial conditions are not met (e.g. bearing not inside beam length) result is set to 0
* and number of errors is increased. Calling class must deal with errors accordingly.
*
* Force, leading sign: (+) Force acts upwards (-) Force acts downwards.
* Torque, leading sing (+) Clockwise (-) Anti- clockwise.
*
* Result: Resulting forces at the bearings can point up or downwards.
* A negative result means that the force points in the opposite direction of the
* acting force. So, (-) means "upwards" regarding the result.
*
*
*
* F1 F2 Fn
* | | |
* -------0--------------------0--------------
* A A
* (F_Left) (F_Right)
*
* |---------- l -------|
*
*
* |
* |-l1---|
* |
* |-------------------l2------|
*
* |x1|
* |
* |--------x2----|
* |
* |----------------xn---------------|
*
*
* Solver calculates from left to right by solving the following equation:
* TorqueSumAtRightBearing=0=F_Leftxl-F1x(l2-x1)-F2x(l2-x2)-....-Fn(l2-xn)
*
* Resulting force at right bearing is calculated by solving this equation:
* SummOfVerticalForces=0=F_Left-F1-F2-....-Fn+F_Right
*
* @author Berthold
*
*/
public class Solve {
public static Result getResults(Beam beam) {
/*
* Init
*/
Result result = new Result();
int errorCount = 0;
double spaceBetweenBearings_m = 0;
double torqueSum = 0;
double loadSum = 0;
Load load;
/*
* Get and check bearings
*/
Bearing leftBearing = beam.getBearing(0);
Bearing rightBearing = beam.getBearing(1);
if (beam.isInsideOfBeamLength(leftBearing.getDistanceFromLeftEndOfBeam_m())
&& beam.isInsideOfBeamLength(rightBearing.getDistanceFromLeftEndOfBeam_m())) {
spaceBetweenBearings_m = Math
.abs(leftBearing.getDistanceFromLeftEndOfBeam_m() - rightBearing.getDistanceFromLeftEndOfBeam_m());
} else
result.setErrorCount(++errorCount);
/*
* Get and check loads, calculate resultant forces at left and right
* bearing
*/
for (int i = 0; i <= beam.getNumberOfLoads() - 1; i++) {
load = beam.getLoad(i);
if (beam.isInsideOfBeamLength(load.getDistanceFromLeftEndOfBeam_m()) && beam
.isInsideOfBeamLength(load.getDistanceFromLeftEndOfBeam_m() + load.getLengthOfLineLoad_m())) {
if (load.getLengthOfLineLoad_m() == 0) {
// Load is a single load
loadSum = loadSum + load.getForce_N();
torqueSum = torqueSum + load.getForce_N()
* (rightBearing.getDistanceFromLeftEndOfBeam_m() - load.getDistanceFromLeftEndOfBeam_m());
} else {
// Load is line load
double resultandForce_N = load.getForce_N() * load.getLengthOfLineLoad_m();
double distanceOfResultandForceFromLeftEndOfbeam_m = (load.getDistanceFromLeftEndOfBeam_m())
+ load.getLengthOfLineLoad_m() / 2;
loadSum = loadSum + resultandForce_N;
torqueSum = torqueSum + resultandForce_N * (rightBearing.getDistanceFromLeftEndOfBeam_m()
- distanceOfResultandForceFromLeftEndOfbeam_m);
}
} else
result.setErrorCount(++errorCount);
}
if (errorCount == 0) {
result.setResultingForceAtLeftBearingBearing_N(-1 * torqueSum / spaceBetweenBearings_m);
result.setResultingForceAtRightBearing_N(-1 * loadSum - result.getResultingForceAtLeftBearing_N());
}
return result;
}
}
The Result:
/**
* Result
*
* TODO: Implement error description....
*
* @author Berthold
*
*/
public class Result {
private int errorCount;
private double resultingForceAtLeftBearing_N, resultingForceAtRightBearing_N;
public int getErrorCount() {
return errorCount;
}
public void setErrorCount(int errorCount) {
this.errorCount = errorCount;
}
public double getResultingForceAtRightBearing_N() {
return resultingForceAtRightBearing_N;
}
public void setResultingForceAtRightBearing_N(double resultingForceAtRightBearing_N) {
this.resultingForceAtRightBearing_N = resultingForceAtRightBearing_N;
}
public double getResultingForceAtLeftBearing_N() {
return resultingForceAtLeftBearing_N;
}
public void setResultingForceAtLeftBearingBearing_N(double resultingForceAtLeftBearing_N) {
this.resultingForceAtLeftBearing_N = resultingForceAtLeftBearing_N;
}
}
Sample application:
/**
* A simple driver
*
* Create a beam, add loads, solve.....
*
*/
public class MainBeamCalculator {
public static void main(String args) {
Beam myBeam = new Beam(12);
myBeam.addBearing(new Bearing(0));
myBeam.addBearing(new Bearing(9));
myBeam.addLoad(new Load(-10, 3, 0));
myBeam.addLoad(new Load(-5, 5, 0));
Result result = Solve.getResults(myBeam);
if (result.getErrorCount() == 0) {
System.out.println("Beam. Loads:" + myBeam.getNumberOfLoads());
System.out.println("Left bearing:" + result.getResultingForceAtLeftBearing_N() + " N. Right bearing:"
+ result.getResultingForceAtRightBearing_N() + " N.");
} else
System.out.println("Errors:" + result.getErrorCount());
}
}
java physics
New contributor
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
36 mins ago
Got your point. So, better repost the old code? Is there any good practice to post improved code based on an answer?
– Berthold Fritz
17 mins ago
Yes, revert to the original code please. This site is not really meant to do "online improvement" If you feel the suggestions raise some confusion create a new question, maybe referencing this one.
– Timothy Truckle
12 mins ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
5 mins ago
add a comment |
I'd like to know if thorwables are good practice to handle semantic errors and if one should always use "getters" and "setters" or if it is ok to access fields in data model objects directly (the load Class).
How do you judge the readibility. Any tips/ hints?
This Class creates a beam:
/**
* A beam.
*
* @author Berthold
*
*/
import java.util.ArrayList;
import java.util.List;
public class Beam {
private double lengthOfBeam_m;
private List<Bearing> support;
private int numberOfBearings;
private List<Load> stress;
/*
* Create a beam
*/
public Beam(double lengthOfBeam_m) {
this.lengthOfBeam_m = lengthOfBeam_m;
support = new ArrayList<Bearing>();
numberOfBearings = 0;
stress = new ArrayList<Load>();
}
/*
* Add load
*/
public void addLoad(Load load) {
stress.add(load);
}
/*
* Add bearing
*/
public void addBearing(Bearing bearing) {
support.add(bearing);
}
/*
* Check if load/ bearing is inside length of beam
*/
public boolean isInsideOfBeamLength(double distanceFromLeftEndOfBeam_m) {
if (distanceFromLeftEndOfBeam_m >= 0 && distanceFromLeftEndOfBeam_m <= lengthOfBeam_m)
return true;
else
return false;
}
/*
* Getters
*/
public Load getLoad(int atIndex) {
return stress.get(atIndex);
}
public double getLength() {
return lengthOfBeam_m;
}
public int getNumberOfLoads() {
return stress.size();
}
public int getNumberOfBearings() {
return numberOfBearings;
}
public Bearing getBearing(int bearingIndexFromLeftEndOfBeam) {
return support.get(bearingIndexFromLeftEndOfBeam);
}
}
This class adds a bearing:
/*
* A Bearing
*/
public class Bearing {
private double distanceFromLeftEndOfBeam_m;
Bearing(double distanceFromLeftEndOfBeam_m) {
this.distanceFromLeftEndOfBeam_m = distanceFromLeftEndOfBeam_m;
}
public double getDistanceFromLeftEndOfBeam_m() {
return distanceFromLeftEndOfBeam_m;
}
}
Load:
/**
* Load
*
* Load acting downwards (-) Load acting upwards (+)
*
* @author Berthold
*
*/
public class Load {
private double force_N;
private double distanceFromLeftEndOfBeam_m;
private double lengthOfLineLoad_m;
/*
* Create a single force or a line load.
*/
public Load(double force_N, double distanceFromLeftEndOfBeam_m, double lengthOfLineLoad_m) {
this.force_N = force_N;
this.distanceFromLeftEndOfBeam_m = distanceFromLeftEndOfBeam_m;
this.lengthOfLineLoad_m = lengthOfLineLoad_m;
}
/*
* Getters
*/
public double getForce_N() {
return force_N;
}
public double getDistanceFromLeftEndOfBeam_m() {
return distanceFromLeftEndOfBeam_m;
}
public double getLengthOfLineLoad_m() {
return lengthOfLineLoad_m;
}
}
This class claculates the beams supporting forces:
/**
* Solves a simply supported beam with single and/ or line loads.
*
* Beam has a statically determined support configuration.
* Bearings may be placed arbitrary inside length of beam.
*
* Solver has to check for valid initial conditions.
* If any of the expected initial conditions are not met (e.g. bearing not inside beam length) result is set to 0
* and number of errors is increased. Calling class must deal with errors accordingly.
*
* Force, leading sign: (+) Force acts upwards (-) Force acts downwards.
* Torque, leading sing (+) Clockwise (-) Anti- clockwise.
*
* Result: Resulting forces at the bearings can point up or downwards.
* A negative result means that the force points in the opposite direction of the
* acting force. So, (-) means "upwards" regarding the result.
*
*
*
* F1 F2 Fn
* | | |
* -------0--------------------0--------------
* A A
* (F_Left) (F_Right)
*
* |---------- l -------|
*
*
* |
* |-l1---|
* |
* |-------------------l2------|
*
* |x1|
* |
* |--------x2----|
* |
* |----------------xn---------------|
*
*
* Solver calculates from left to right by solving the following equation:
* TorqueSumAtRightBearing=0=F_Leftxl-F1x(l2-x1)-F2x(l2-x2)-....-Fn(l2-xn)
*
* Resulting force at right bearing is calculated by solving this equation:
* SummOfVerticalForces=0=F_Left-F1-F2-....-Fn+F_Right
*
* @author Berthold
*
*/
public class Solve {
public static Result getResults(Beam beam) {
/*
* Init
*/
Result result = new Result();
int errorCount = 0;
double spaceBetweenBearings_m = 0;
double torqueSum = 0;
double loadSum = 0;
Load load;
/*
* Get and check bearings
*/
Bearing leftBearing = beam.getBearing(0);
Bearing rightBearing = beam.getBearing(1);
if (beam.isInsideOfBeamLength(leftBearing.getDistanceFromLeftEndOfBeam_m())
&& beam.isInsideOfBeamLength(rightBearing.getDistanceFromLeftEndOfBeam_m())) {
spaceBetweenBearings_m = Math
.abs(leftBearing.getDistanceFromLeftEndOfBeam_m() - rightBearing.getDistanceFromLeftEndOfBeam_m());
} else
result.setErrorCount(++errorCount);
/*
* Get and check loads, calculate resultant forces at left and right
* bearing
*/
for (int i = 0; i <= beam.getNumberOfLoads() - 1; i++) {
load = beam.getLoad(i);
if (beam.isInsideOfBeamLength(load.getDistanceFromLeftEndOfBeam_m()) && beam
.isInsideOfBeamLength(load.getDistanceFromLeftEndOfBeam_m() + load.getLengthOfLineLoad_m())) {
if (load.getLengthOfLineLoad_m() == 0) {
// Load is a single load
loadSum = loadSum + load.getForce_N();
torqueSum = torqueSum + load.getForce_N()
* (rightBearing.getDistanceFromLeftEndOfBeam_m() - load.getDistanceFromLeftEndOfBeam_m());
} else {
// Load is line load
double resultandForce_N = load.getForce_N() * load.getLengthOfLineLoad_m();
double distanceOfResultandForceFromLeftEndOfbeam_m = (load.getDistanceFromLeftEndOfBeam_m())
+ load.getLengthOfLineLoad_m() / 2;
loadSum = loadSum + resultandForce_N;
torqueSum = torqueSum + resultandForce_N * (rightBearing.getDistanceFromLeftEndOfBeam_m()
- distanceOfResultandForceFromLeftEndOfbeam_m);
}
} else
result.setErrorCount(++errorCount);
}
if (errorCount == 0) {
result.setResultingForceAtLeftBearingBearing_N(-1 * torqueSum / spaceBetweenBearings_m);
result.setResultingForceAtRightBearing_N(-1 * loadSum - result.getResultingForceAtLeftBearing_N());
}
return result;
}
}
The Result:
/**
* Result
*
* TODO: Implement error description....
*
* @author Berthold
*
*/
public class Result {
private int errorCount;
private double resultingForceAtLeftBearing_N, resultingForceAtRightBearing_N;
public int getErrorCount() {
return errorCount;
}
public void setErrorCount(int errorCount) {
this.errorCount = errorCount;
}
public double getResultingForceAtRightBearing_N() {
return resultingForceAtRightBearing_N;
}
public void setResultingForceAtRightBearing_N(double resultingForceAtRightBearing_N) {
this.resultingForceAtRightBearing_N = resultingForceAtRightBearing_N;
}
public double getResultingForceAtLeftBearing_N() {
return resultingForceAtLeftBearing_N;
}
public void setResultingForceAtLeftBearingBearing_N(double resultingForceAtLeftBearing_N) {
this.resultingForceAtLeftBearing_N = resultingForceAtLeftBearing_N;
}
}
Sample application:
/**
* A simple driver
*
* Create a beam, add loads, solve.....
*
*/
public class MainBeamCalculator {
public static void main(String args) {
Beam myBeam = new Beam(12);
myBeam.addBearing(new Bearing(0));
myBeam.addBearing(new Bearing(9));
myBeam.addLoad(new Load(-10, 3, 0));
myBeam.addLoad(new Load(-5, 5, 0));
Result result = Solve.getResults(myBeam);
if (result.getErrorCount() == 0) {
System.out.println("Beam. Loads:" + myBeam.getNumberOfLoads());
System.out.println("Left bearing:" + result.getResultingForceAtLeftBearing_N() + " N. Right bearing:"
+ result.getResultingForceAtRightBearing_N() + " N.");
} else
System.out.println("Errors:" + result.getErrorCount());
}
}
java physics
New contributor
I'd like to know if thorwables are good practice to handle semantic errors and if one should always use "getters" and "setters" or if it is ok to access fields in data model objects directly (the load Class).
How do you judge the readibility. Any tips/ hints?
This Class creates a beam:
/**
* A beam.
*
* @author Berthold
*
*/
import java.util.ArrayList;
import java.util.List;
public class Beam {
private double lengthOfBeam_m;
private List<Bearing> support;
private int numberOfBearings;
private List<Load> stress;
/*
* Create a beam
*/
public Beam(double lengthOfBeam_m) {
this.lengthOfBeam_m = lengthOfBeam_m;
support = new ArrayList<Bearing>();
numberOfBearings = 0;
stress = new ArrayList<Load>();
}
/*
* Add load
*/
public void addLoad(Load load) {
stress.add(load);
}
/*
* Add bearing
*/
public void addBearing(Bearing bearing) {
support.add(bearing);
}
/*
* Check if load/ bearing is inside length of beam
*/
public boolean isInsideOfBeamLength(double distanceFromLeftEndOfBeam_m) {
if (distanceFromLeftEndOfBeam_m >= 0 && distanceFromLeftEndOfBeam_m <= lengthOfBeam_m)
return true;
else
return false;
}
/*
* Getters
*/
public Load getLoad(int atIndex) {
return stress.get(atIndex);
}
public double getLength() {
return lengthOfBeam_m;
}
public int getNumberOfLoads() {
return stress.size();
}
public int getNumberOfBearings() {
return numberOfBearings;
}
public Bearing getBearing(int bearingIndexFromLeftEndOfBeam) {
return support.get(bearingIndexFromLeftEndOfBeam);
}
}
This class adds a bearing:
/*
* A Bearing
*/
public class Bearing {
private double distanceFromLeftEndOfBeam_m;
Bearing(double distanceFromLeftEndOfBeam_m) {
this.distanceFromLeftEndOfBeam_m = distanceFromLeftEndOfBeam_m;
}
public double getDistanceFromLeftEndOfBeam_m() {
return distanceFromLeftEndOfBeam_m;
}
}
Load:
/**
* Load
*
* Load acting downwards (-) Load acting upwards (+)
*
* @author Berthold
*
*/
public class Load {
private double force_N;
private double distanceFromLeftEndOfBeam_m;
private double lengthOfLineLoad_m;
/*
* Create a single force or a line load.
*/
public Load(double force_N, double distanceFromLeftEndOfBeam_m, double lengthOfLineLoad_m) {
this.force_N = force_N;
this.distanceFromLeftEndOfBeam_m = distanceFromLeftEndOfBeam_m;
this.lengthOfLineLoad_m = lengthOfLineLoad_m;
}
/*
* Getters
*/
public double getForce_N() {
return force_N;
}
public double getDistanceFromLeftEndOfBeam_m() {
return distanceFromLeftEndOfBeam_m;
}
public double getLengthOfLineLoad_m() {
return lengthOfLineLoad_m;
}
}
This class claculates the beams supporting forces:
/**
* Solves a simply supported beam with single and/ or line loads.
*
* Beam has a statically determined support configuration.
* Bearings may be placed arbitrary inside length of beam.
*
* Solver has to check for valid initial conditions.
* If any of the expected initial conditions are not met (e.g. bearing not inside beam length) result is set to 0
* and number of errors is increased. Calling class must deal with errors accordingly.
*
* Force, leading sign: (+) Force acts upwards (-) Force acts downwards.
* Torque, leading sing (+) Clockwise (-) Anti- clockwise.
*
* Result: Resulting forces at the bearings can point up or downwards.
* A negative result means that the force points in the opposite direction of the
* acting force. So, (-) means "upwards" regarding the result.
*
*
*
* F1 F2 Fn
* | | |
* -------0--------------------0--------------
* A A
* (F_Left) (F_Right)
*
* |---------- l -------|
*
*
* |
* |-l1---|
* |
* |-------------------l2------|
*
* |x1|
* |
* |--------x2----|
* |
* |----------------xn---------------|
*
*
* Solver calculates from left to right by solving the following equation:
* TorqueSumAtRightBearing=0=F_Leftxl-F1x(l2-x1)-F2x(l2-x2)-....-Fn(l2-xn)
*
* Resulting force at right bearing is calculated by solving this equation:
* SummOfVerticalForces=0=F_Left-F1-F2-....-Fn+F_Right
*
* @author Berthold
*
*/
public class Solve {
public static Result getResults(Beam beam) {
/*
* Init
*/
Result result = new Result();
int errorCount = 0;
double spaceBetweenBearings_m = 0;
double torqueSum = 0;
double loadSum = 0;
Load load;
/*
* Get and check bearings
*/
Bearing leftBearing = beam.getBearing(0);
Bearing rightBearing = beam.getBearing(1);
if (beam.isInsideOfBeamLength(leftBearing.getDistanceFromLeftEndOfBeam_m())
&& beam.isInsideOfBeamLength(rightBearing.getDistanceFromLeftEndOfBeam_m())) {
spaceBetweenBearings_m = Math
.abs(leftBearing.getDistanceFromLeftEndOfBeam_m() - rightBearing.getDistanceFromLeftEndOfBeam_m());
} else
result.setErrorCount(++errorCount);
/*
* Get and check loads, calculate resultant forces at left and right
* bearing
*/
for (int i = 0; i <= beam.getNumberOfLoads() - 1; i++) {
load = beam.getLoad(i);
if (beam.isInsideOfBeamLength(load.getDistanceFromLeftEndOfBeam_m()) && beam
.isInsideOfBeamLength(load.getDistanceFromLeftEndOfBeam_m() + load.getLengthOfLineLoad_m())) {
if (load.getLengthOfLineLoad_m() == 0) {
// Load is a single load
loadSum = loadSum + load.getForce_N();
torqueSum = torqueSum + load.getForce_N()
* (rightBearing.getDistanceFromLeftEndOfBeam_m() - load.getDistanceFromLeftEndOfBeam_m());
} else {
// Load is line load
double resultandForce_N = load.getForce_N() * load.getLengthOfLineLoad_m();
double distanceOfResultandForceFromLeftEndOfbeam_m = (load.getDistanceFromLeftEndOfBeam_m())
+ load.getLengthOfLineLoad_m() / 2;
loadSum = loadSum + resultandForce_N;
torqueSum = torqueSum + resultandForce_N * (rightBearing.getDistanceFromLeftEndOfBeam_m()
- distanceOfResultandForceFromLeftEndOfbeam_m);
}
} else
result.setErrorCount(++errorCount);
}
if (errorCount == 0) {
result.setResultingForceAtLeftBearingBearing_N(-1 * torqueSum / spaceBetweenBearings_m);
result.setResultingForceAtRightBearing_N(-1 * loadSum - result.getResultingForceAtLeftBearing_N());
}
return result;
}
}
The Result:
/**
* Result
*
* TODO: Implement error description....
*
* @author Berthold
*
*/
public class Result {
private int errorCount;
private double resultingForceAtLeftBearing_N, resultingForceAtRightBearing_N;
public int getErrorCount() {
return errorCount;
}
public void setErrorCount(int errorCount) {
this.errorCount = errorCount;
}
public double getResultingForceAtRightBearing_N() {
return resultingForceAtRightBearing_N;
}
public void setResultingForceAtRightBearing_N(double resultingForceAtRightBearing_N) {
this.resultingForceAtRightBearing_N = resultingForceAtRightBearing_N;
}
public double getResultingForceAtLeftBearing_N() {
return resultingForceAtLeftBearing_N;
}
public void setResultingForceAtLeftBearingBearing_N(double resultingForceAtLeftBearing_N) {
this.resultingForceAtLeftBearing_N = resultingForceAtLeftBearing_N;
}
}
Sample application:
/**
* A simple driver
*
* Create a beam, add loads, solve.....
*
*/
public class MainBeamCalculator {
public static void main(String args) {
Beam myBeam = new Beam(12);
myBeam.addBearing(new Bearing(0));
myBeam.addBearing(new Bearing(9));
myBeam.addLoad(new Load(-10, 3, 0));
myBeam.addLoad(new Load(-5, 5, 0));
Result result = Solve.getResults(myBeam);
if (result.getErrorCount() == 0) {
System.out.println("Beam. Loads:" + myBeam.getNumberOfLoads());
System.out.println("Left bearing:" + result.getResultingForceAtLeftBearing_N() + " N. Right bearing:"
+ result.getResultingForceAtRightBearing_N() + " N.");
} else
System.out.println("Errors:" + result.getErrorCount());
}
}
java physics
java physics
New contributor
New contributor
edited 57 mins ago
New contributor
asked Dec 23 at 20:46
Berthold Fritz
113
113
New contributor
New contributor
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
36 mins ago
Got your point. So, better repost the old code? Is there any good practice to post improved code based on an answer?
– Berthold Fritz
17 mins ago
Yes, revert to the original code please. This site is not really meant to do "online improvement" If you feel the suggestions raise some confusion create a new question, maybe referencing this one.
– Timothy Truckle
12 mins ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
5 mins ago
add a comment |
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
36 mins ago
Got your point. So, better repost the old code? Is there any good practice to post improved code based on an answer?
– Berthold Fritz
17 mins ago
Yes, revert to the original code please. This site is not really meant to do "online improvement" If you feel the suggestions raise some confusion create a new question, maybe referencing this one.
– Timothy Truckle
12 mins ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
5 mins ago
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
36 mins ago
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
36 mins ago
Got your point. So, better repost the old code? Is there any good practice to post improved code based on an answer?
– Berthold Fritz
17 mins ago
Got your point. So, better repost the old code? Is there any good practice to post improved code based on an answer?
– Berthold Fritz
17 mins ago
Yes, revert to the original code please. This site is not really meant to do "online improvement" If you feel the suggestions raise some confusion create a new question, maybe referencing this one.
– Timothy Truckle
12 mins ago
Yes, revert to the original code please. This site is not really meant to do "online improvement" If you feel the suggestions raise some confusion create a new question, maybe referencing this one.
– Timothy Truckle
12 mins ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
5 mins ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
5 mins ago
add a comment |
1 Answer
1
active
oldest
votes
Thanks for sharing your code.
thorwables are good practice to handle semantic errors?
There is an argument running in the community when exactly exceptions should be used and when not. You might get different answers depending on who you ask.
The common ground here ist that exceptions should not be misused to control the program flow.
IMHO your use of the exception is ok since the detected situation needs user interaction to be solved. The there is no way the program can recover from that on its own.
one should always use "getters" and "setters"?
Yes.
The reason is that your Load
class may develop and get Extentions (specialized Loads that extend your currrent Load
class). Or you decide to change the way your Load
class stores its properties. accessing the properties via getter and setter yould enable you to change that without affecting the calling code.
Some may argue that this is overkill for such a small problem, but you should get used to do so "in principle".
BUT
This holds only true for Data Transfer Objects or Value Objects, anything that can be considered being the "Data Model".
Classes holding business logic should not have getters or setters.
How do you judge the readibility.
Comments
Your code has a lot of comments.
Some decades ago this was concidered a good thing but currently the we agree that less is more.
Comments should explain why the code is like it is. Your identifiers (names of methods and variables) should explain how it works.
The reason is that comments thend to erode.
While your program develops you change the code but not the comments for various resons: no time, to concentrated or something along that.
You intent to change the comment later but that never happens usually for the same reasons you did noch change it immediately.
This way youir comments turn into lies while the code they used to describe changes.
good comments
Yes, your code also has good comments. ;o)
The header comment of class Solution
is a good one.
It describes what the code is supposed to do.
bad comments
variable explanations
repetition
public double force; // Force
This is just a repetition of the name.
It adds no value for the reader.
single character names / explained variables
In Java the length of identifiers is virtually unbounded.
There is no need to be stingy with characters.
Instead of that explanation in classLoad
public double x; // x= length from beginning of the girder to the force acting
the variable could be named like this
public double distanceFromMount;
the same applies to variable
length
public double lineLoadLegth;
BTW: when dealing with physical values it is a good idea to add units to identifier names.
Remember the failed Mars missions Mars Climate Orbiter and Mars Polar Lander?
They failed because the main computer was build by NASA and as usual in science they handled physical values in SI units (km, km/h, kg) while the lander engine was build by General Electrics aviation department where engineers traditionally use imperial units (miles, knots, pounds) Since they did not had units in their identifiers this problem could not be detected by code reviews or the engineers while coding.
So even when not coding space mission control software you should consider adding units to variables (and method) dealing with physical values as the properties in your Load
class do:
public double forceInNewton;
public double distanceFromMountInMeter;
public double loadLengthInMeter;
I'd even consider this being a valid reason to violate the Naming Conventions and write it like this:
public double force_N;
public double distanceFromMount_m;
public double loadLength_ft;
code formatting
Put each instruction on a separate line.
So the method addLoad
in class Beam
should look like this:
public void addLoad(Load load) throws BeamError {
if (load.x>=0 && load.x<=length && load.x+load.length<=length)
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
You may consider to use your IDEs *auto formatter" feature to always have proper line breaks and indentation.
use private methods
The method addLoad
in class Beam
has some more readability issue.
It is not obvious what the condition is.
So it might be a good idea to move that into a method of its own:
private boolean isInside(Load load) throws BeamError {
return load.x>=0 && load.x<=length && load.x+load.length<=length;
}
public void addLoad(Load load) throws BeamError {
if (isInside(load))
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
separation of concerns (from readability point of view)
Being inside class Beam
the line
if (isInside(load))
still reads a bit "bumpy", whereas
public void addLoad(Load load) throws BeamError {
if (load.isInside(length_m))
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
is much more expressive (IMHO).
This could be an indication that isInside()
belongs to class Load
rather than to class Beam
.
Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly.
– Berthold Fritz
48 mins ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Berthold Fritz is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210241%2fcalculate-supporting-forces-of-an-simply-supported-beam%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for sharing your code.
thorwables are good practice to handle semantic errors?
There is an argument running in the community when exactly exceptions should be used and when not. You might get different answers depending on who you ask.
The common ground here ist that exceptions should not be misused to control the program flow.
IMHO your use of the exception is ok since the detected situation needs user interaction to be solved. The there is no way the program can recover from that on its own.
one should always use "getters" and "setters"?
Yes.
The reason is that your Load
class may develop and get Extentions (specialized Loads that extend your currrent Load
class). Or you decide to change the way your Load
class stores its properties. accessing the properties via getter and setter yould enable you to change that without affecting the calling code.
Some may argue that this is overkill for such a small problem, but you should get used to do so "in principle".
BUT
This holds only true for Data Transfer Objects or Value Objects, anything that can be considered being the "Data Model".
Classes holding business logic should not have getters or setters.
How do you judge the readibility.
Comments
Your code has a lot of comments.
Some decades ago this was concidered a good thing but currently the we agree that less is more.
Comments should explain why the code is like it is. Your identifiers (names of methods and variables) should explain how it works.
The reason is that comments thend to erode.
While your program develops you change the code but not the comments for various resons: no time, to concentrated or something along that.
You intent to change the comment later but that never happens usually for the same reasons you did noch change it immediately.
This way youir comments turn into lies while the code they used to describe changes.
good comments
Yes, your code also has good comments. ;o)
The header comment of class Solution
is a good one.
It describes what the code is supposed to do.
bad comments
variable explanations
repetition
public double force; // Force
This is just a repetition of the name.
It adds no value for the reader.
single character names / explained variables
In Java the length of identifiers is virtually unbounded.
There is no need to be stingy with characters.
Instead of that explanation in classLoad
public double x; // x= length from beginning of the girder to the force acting
the variable could be named like this
public double distanceFromMount;
the same applies to variable
length
public double lineLoadLegth;
BTW: when dealing with physical values it is a good idea to add units to identifier names.
Remember the failed Mars missions Mars Climate Orbiter and Mars Polar Lander?
They failed because the main computer was build by NASA and as usual in science they handled physical values in SI units (km, km/h, kg) while the lander engine was build by General Electrics aviation department where engineers traditionally use imperial units (miles, knots, pounds) Since they did not had units in their identifiers this problem could not be detected by code reviews or the engineers while coding.
So even when not coding space mission control software you should consider adding units to variables (and method) dealing with physical values as the properties in your Load
class do:
public double forceInNewton;
public double distanceFromMountInMeter;
public double loadLengthInMeter;
I'd even consider this being a valid reason to violate the Naming Conventions and write it like this:
public double force_N;
public double distanceFromMount_m;
public double loadLength_ft;
code formatting
Put each instruction on a separate line.
So the method addLoad
in class Beam
should look like this:
public void addLoad(Load load) throws BeamError {
if (load.x>=0 && load.x<=length && load.x+load.length<=length)
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
You may consider to use your IDEs *auto formatter" feature to always have proper line breaks and indentation.
use private methods
The method addLoad
in class Beam
has some more readability issue.
It is not obvious what the condition is.
So it might be a good idea to move that into a method of its own:
private boolean isInside(Load load) throws BeamError {
return load.x>=0 && load.x<=length && load.x+load.length<=length;
}
public void addLoad(Load load) throws BeamError {
if (isInside(load))
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
separation of concerns (from readability point of view)
Being inside class Beam
the line
if (isInside(load))
still reads a bit "bumpy", whereas
public void addLoad(Load load) throws BeamError {
if (load.isInside(length_m))
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
is much more expressive (IMHO).
This could be an indication that isInside()
belongs to class Load
rather than to class Beam
.
Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly.
– Berthold Fritz
48 mins ago
add a comment |
Thanks for sharing your code.
thorwables are good practice to handle semantic errors?
There is an argument running in the community when exactly exceptions should be used and when not. You might get different answers depending on who you ask.
The common ground here ist that exceptions should not be misused to control the program flow.
IMHO your use of the exception is ok since the detected situation needs user interaction to be solved. The there is no way the program can recover from that on its own.
one should always use "getters" and "setters"?
Yes.
The reason is that your Load
class may develop and get Extentions (specialized Loads that extend your currrent Load
class). Or you decide to change the way your Load
class stores its properties. accessing the properties via getter and setter yould enable you to change that without affecting the calling code.
Some may argue that this is overkill for such a small problem, but you should get used to do so "in principle".
BUT
This holds only true for Data Transfer Objects or Value Objects, anything that can be considered being the "Data Model".
Classes holding business logic should not have getters or setters.
How do you judge the readibility.
Comments
Your code has a lot of comments.
Some decades ago this was concidered a good thing but currently the we agree that less is more.
Comments should explain why the code is like it is. Your identifiers (names of methods and variables) should explain how it works.
The reason is that comments thend to erode.
While your program develops you change the code but not the comments for various resons: no time, to concentrated or something along that.
You intent to change the comment later but that never happens usually for the same reasons you did noch change it immediately.
This way youir comments turn into lies while the code they used to describe changes.
good comments
Yes, your code also has good comments. ;o)
The header comment of class Solution
is a good one.
It describes what the code is supposed to do.
bad comments
variable explanations
repetition
public double force; // Force
This is just a repetition of the name.
It adds no value for the reader.
single character names / explained variables
In Java the length of identifiers is virtually unbounded.
There is no need to be stingy with characters.
Instead of that explanation in classLoad
public double x; // x= length from beginning of the girder to the force acting
the variable could be named like this
public double distanceFromMount;
the same applies to variable
length
public double lineLoadLegth;
BTW: when dealing with physical values it is a good idea to add units to identifier names.
Remember the failed Mars missions Mars Climate Orbiter and Mars Polar Lander?
They failed because the main computer was build by NASA and as usual in science they handled physical values in SI units (km, km/h, kg) while the lander engine was build by General Electrics aviation department where engineers traditionally use imperial units (miles, knots, pounds) Since they did not had units in their identifiers this problem could not be detected by code reviews or the engineers while coding.
So even when not coding space mission control software you should consider adding units to variables (and method) dealing with physical values as the properties in your Load
class do:
public double forceInNewton;
public double distanceFromMountInMeter;
public double loadLengthInMeter;
I'd even consider this being a valid reason to violate the Naming Conventions and write it like this:
public double force_N;
public double distanceFromMount_m;
public double loadLength_ft;
code formatting
Put each instruction on a separate line.
So the method addLoad
in class Beam
should look like this:
public void addLoad(Load load) throws BeamError {
if (load.x>=0 && load.x<=length && load.x+load.length<=length)
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
You may consider to use your IDEs *auto formatter" feature to always have proper line breaks and indentation.
use private methods
The method addLoad
in class Beam
has some more readability issue.
It is not obvious what the condition is.
So it might be a good idea to move that into a method of its own:
private boolean isInside(Load load) throws BeamError {
return load.x>=0 && load.x<=length && load.x+load.length<=length;
}
public void addLoad(Load load) throws BeamError {
if (isInside(load))
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
separation of concerns (from readability point of view)
Being inside class Beam
the line
if (isInside(load))
still reads a bit "bumpy", whereas
public void addLoad(Load load) throws BeamError {
if (load.isInside(length_m))
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
is much more expressive (IMHO).
This could be an indication that isInside()
belongs to class Load
rather than to class Beam
.
Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly.
– Berthold Fritz
48 mins ago
add a comment |
Thanks for sharing your code.
thorwables are good practice to handle semantic errors?
There is an argument running in the community when exactly exceptions should be used and when not. You might get different answers depending on who you ask.
The common ground here ist that exceptions should not be misused to control the program flow.
IMHO your use of the exception is ok since the detected situation needs user interaction to be solved. The there is no way the program can recover from that on its own.
one should always use "getters" and "setters"?
Yes.
The reason is that your Load
class may develop and get Extentions (specialized Loads that extend your currrent Load
class). Or you decide to change the way your Load
class stores its properties. accessing the properties via getter and setter yould enable you to change that without affecting the calling code.
Some may argue that this is overkill for such a small problem, but you should get used to do so "in principle".
BUT
This holds only true for Data Transfer Objects or Value Objects, anything that can be considered being the "Data Model".
Classes holding business logic should not have getters or setters.
How do you judge the readibility.
Comments
Your code has a lot of comments.
Some decades ago this was concidered a good thing but currently the we agree that less is more.
Comments should explain why the code is like it is. Your identifiers (names of methods and variables) should explain how it works.
The reason is that comments thend to erode.
While your program develops you change the code but not the comments for various resons: no time, to concentrated or something along that.
You intent to change the comment later but that never happens usually for the same reasons you did noch change it immediately.
This way youir comments turn into lies while the code they used to describe changes.
good comments
Yes, your code also has good comments. ;o)
The header comment of class Solution
is a good one.
It describes what the code is supposed to do.
bad comments
variable explanations
repetition
public double force; // Force
This is just a repetition of the name.
It adds no value for the reader.
single character names / explained variables
In Java the length of identifiers is virtually unbounded.
There is no need to be stingy with characters.
Instead of that explanation in classLoad
public double x; // x= length from beginning of the girder to the force acting
the variable could be named like this
public double distanceFromMount;
the same applies to variable
length
public double lineLoadLegth;
BTW: when dealing with physical values it is a good idea to add units to identifier names.
Remember the failed Mars missions Mars Climate Orbiter and Mars Polar Lander?
They failed because the main computer was build by NASA and as usual in science they handled physical values in SI units (km, km/h, kg) while the lander engine was build by General Electrics aviation department where engineers traditionally use imperial units (miles, knots, pounds) Since they did not had units in their identifiers this problem could not be detected by code reviews or the engineers while coding.
So even when not coding space mission control software you should consider adding units to variables (and method) dealing with physical values as the properties in your Load
class do:
public double forceInNewton;
public double distanceFromMountInMeter;
public double loadLengthInMeter;
I'd even consider this being a valid reason to violate the Naming Conventions and write it like this:
public double force_N;
public double distanceFromMount_m;
public double loadLength_ft;
code formatting
Put each instruction on a separate line.
So the method addLoad
in class Beam
should look like this:
public void addLoad(Load load) throws BeamError {
if (load.x>=0 && load.x<=length && load.x+load.length<=length)
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
You may consider to use your IDEs *auto formatter" feature to always have proper line breaks and indentation.
use private methods
The method addLoad
in class Beam
has some more readability issue.
It is not obvious what the condition is.
So it might be a good idea to move that into a method of its own:
private boolean isInside(Load load) throws BeamError {
return load.x>=0 && load.x<=length && load.x+load.length<=length;
}
public void addLoad(Load load) throws BeamError {
if (isInside(load))
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
separation of concerns (from readability point of view)
Being inside class Beam
the line
if (isInside(load))
still reads a bit "bumpy", whereas
public void addLoad(Load load) throws BeamError {
if (load.isInside(length_m))
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
is much more expressive (IMHO).
This could be an indication that isInside()
belongs to class Load
rather than to class Beam
.
Thanks for sharing your code.
thorwables are good practice to handle semantic errors?
There is an argument running in the community when exactly exceptions should be used and when not. You might get different answers depending on who you ask.
The common ground here ist that exceptions should not be misused to control the program flow.
IMHO your use of the exception is ok since the detected situation needs user interaction to be solved. The there is no way the program can recover from that on its own.
one should always use "getters" and "setters"?
Yes.
The reason is that your Load
class may develop and get Extentions (specialized Loads that extend your currrent Load
class). Or you decide to change the way your Load
class stores its properties. accessing the properties via getter and setter yould enable you to change that without affecting the calling code.
Some may argue that this is overkill for such a small problem, but you should get used to do so "in principle".
BUT
This holds only true for Data Transfer Objects or Value Objects, anything that can be considered being the "Data Model".
Classes holding business logic should not have getters or setters.
How do you judge the readibility.
Comments
Your code has a lot of comments.
Some decades ago this was concidered a good thing but currently the we agree that less is more.
Comments should explain why the code is like it is. Your identifiers (names of methods and variables) should explain how it works.
The reason is that comments thend to erode.
While your program develops you change the code but not the comments for various resons: no time, to concentrated or something along that.
You intent to change the comment later but that never happens usually for the same reasons you did noch change it immediately.
This way youir comments turn into lies while the code they used to describe changes.
good comments
Yes, your code also has good comments. ;o)
The header comment of class Solution
is a good one.
It describes what the code is supposed to do.
bad comments
variable explanations
repetition
public double force; // Force
This is just a repetition of the name.
It adds no value for the reader.
single character names / explained variables
In Java the length of identifiers is virtually unbounded.
There is no need to be stingy with characters.
Instead of that explanation in classLoad
public double x; // x= length from beginning of the girder to the force acting
the variable could be named like this
public double distanceFromMount;
the same applies to variable
length
public double lineLoadLegth;
BTW: when dealing with physical values it is a good idea to add units to identifier names.
Remember the failed Mars missions Mars Climate Orbiter and Mars Polar Lander?
They failed because the main computer was build by NASA and as usual in science they handled physical values in SI units (km, km/h, kg) while the lander engine was build by General Electrics aviation department where engineers traditionally use imperial units (miles, knots, pounds) Since they did not had units in their identifiers this problem could not be detected by code reviews or the engineers while coding.
So even when not coding space mission control software you should consider adding units to variables (and method) dealing with physical values as the properties in your Load
class do:
public double forceInNewton;
public double distanceFromMountInMeter;
public double loadLengthInMeter;
I'd even consider this being a valid reason to violate the Naming Conventions and write it like this:
public double force_N;
public double distanceFromMount_m;
public double loadLength_ft;
code formatting
Put each instruction on a separate line.
So the method addLoad
in class Beam
should look like this:
public void addLoad(Load load) throws BeamError {
if (load.x>=0 && load.x<=length && load.x+load.length<=length)
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
You may consider to use your IDEs *auto formatter" feature to always have proper line breaks and indentation.
use private methods
The method addLoad
in class Beam
has some more readability issue.
It is not obvious what the condition is.
So it might be a good idea to move that into a method of its own:
private boolean isInside(Load load) throws BeamError {
return load.x>=0 && load.x<=length && load.x+load.length<=length;
}
public void addLoad(Load load) throws BeamError {
if (isInside(load))
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
separation of concerns (from readability point of view)
Being inside class Beam
the line
if (isInside(load))
still reads a bit "bumpy", whereas
public void addLoad(Load load) throws BeamError {
if (load.isInside(length_m))
stress.add(load);
else
throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
is much more expressive (IMHO).
This could be an indication that isInside()
belongs to class Load
rather than to class Beam
.
edited 38 mins ago
answered 2 days ago
Timothy Truckle
4,828416
4,828416
Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly.
– Berthold Fritz
48 mins ago
add a comment |
Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly.
– Berthold Fritz
48 mins ago
Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly.
– Berthold Fritz
48 mins ago
Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly.
– Berthold Fritz
48 mins ago
add a comment |
Berthold Fritz is a new contributor. Be nice, and check out our Code of Conduct.
Berthold Fritz is a new contributor. Be nice, and check out our Code of Conduct.
Berthold Fritz is a new contributor. Be nice, and check out our Code of Conduct.
Berthold Fritz is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210241%2fcalculate-supporting-forces-of-an-simply-supported-beam%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
36 mins ago
Got your point. So, better repost the old code? Is there any good practice to post improved code based on an answer?
– Berthold Fritz
17 mins ago
Yes, revert to the original code please. This site is not really meant to do "online improvement" If you feel the suggestions raise some confusion create a new question, maybe referencing this one.
– Timothy Truckle
12 mins ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
5 mins ago