Calculate supporting forces of a simply supported beam
The program uses a very simple algorithm to calculate the supporting forces of a 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 simply supported beam.
*
* @author Berthold
*
*/
import java.util.ArrayList;
import java.util.List;
public class Beam {
private double length;
private List <Load> stress;
/*
* Create a beam
*/
public Beam(double length){
this.length=length;
stress=new ArrayList<Load> ();
}
/*
* Add load
*/
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);
}
/*
* Get load
*/
public Load getLoad(int atIndex){
return stress.get(atIndex);
}
/*
* Get length
*/
public double getLength(){
return length;
}
/*
* Return # of loads acting
*/
public int numberOfLoads(){
return stress.size();
}
}
This Class adds a load:
/**
* Load
*
* Load acting downwards -
* Load acting upwards +
*
* Single load: length=0
* line load: x=distance from bearing A. Length= length of line load
*
* @author Berthold
*
*/
public class Load {
public double force; // Force
public double x; // x= length from beginning of the girder to the force acting
public double length;// If not 0 => force is a line load. Starts at x, ends at x+l
/*
* Create a single force or a line load.
*/
public Load (double force,double x,double length){
this.force=force;
this.x=x;
this.length=length;
}
}
This class claculates the beams supporting forces:
/**
* Solves a simply supported beam with single and/ or line loads.
*
* Beam is not cantilevered (two bearings, one at the beginning, one at the end).
* Beam has a statically determined support configuration.
*
* Force, leading sign:
* + Force acts upwards
* - Force acts downwards
*
* Torque, leading sing
* + Clockwise
* - Anti- clockwise
*
* Bearings
* A is left, B is right
* A is pinned
* B is a roller
*
* Length
* Starts at A (0) and ends at B(l)
*
* 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
* o-------------------------------o
* A B
* |---------x1----x2---xn
* |
* |--------------- l -------------|
*
* x=0 x=l
*
* Solver calculates from left to right by solving the following equation
* (Result is resulting force at bearing A):
* Sum M=0=FA x l - F1 x (l-x1) - F2(l-x2) x ..... x Fn(l-xn)
*
* Resulting force at bearing B is calculated by solving this equation:
* Sum V=0=FA-F1-F2-....-Fn+FB
*
* @author Berthold
*
*/
public class Solve {
/*
* Get result
*/
public static Result getResults(Beam beam){
Result r=new Result();
double torqueSum=0;
double loadSum=0;
Load load;
for (int i=0;i<=beam.numberOfLoads()-1;i++){
load=beam.getLoad(i);
// Check if load is a single load
if (load.length==0){
loadSum=loadSum+load.force;
torqueSum=torqueSum+load.force*(beam.getLength()-load.x);
// Line load
} else{
double xx=(beam.getLength()-load.x)-load.length/2;
double ff=load.force*load.length;
loadSum=loadSum+ff;
torqueSum=torqueSum+loadSum*xx;
}
}
// We multiply by -1 to get the right direction of the force at the bearing.
// Remember: Per our convention - means the force points downward (globally).
// For the result - means it points in the opposite direction of the acting forces,
// so it points upwards.....
// FA=(Sum Fn x xn)/l
r.bearingA=-1*torqueSum/beam.getLength();
// FB=Sum F - FA
r.bearingB=-1*loadSum-r.bearingA;
return r;
}
}
Error handling:
/**
* BeamError
*
* Describes an error occured while creating a new beam or
* setting it's properties.
*
* @author Berthold
*
*/
public class BeamError extends Throwable{
String errorDescription;
int loadNumberCausedError;
public BeamError(String errorDescription,int loadNumberCausedError){
this.errorDescription=errorDescription;
this.loadNumberCausedError=loadNumberCausedError;
}
}
Main Class, shows how to use the package:
/**
* A simple driver
*
* Create a beam, add loads, solve.....
*
*/
public class MainBeamCalculator {
public static void main(String args){
// A girder, length=10 m
Beam myBeam=new Beam (15);
// Add some stress
try{
myBeam.addLoad(new Load(-5.5,1,0));
myBeam.addLoad(new Load(-2,4,0));
myBeam.addLoad(new Load(-3,8,0));
// Get results
System.out.println("Beam. Loads:"+myBeam.numberOfLoads());
Result r=Solve.getResults(myBeam);
System.out.println("Bearing A:"+r.bearingA+" B:"+r.bearingB);
}catch (BeamError e){
System.out.println ("Error while creating beam:"+e.errorDescription);
System.out.println("Load #"+e.loadNumberCausedError+" wrong!");
}
}
}
java physics
New contributor
add a comment |
The program uses a very simple algorithm to calculate the supporting forces of a 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 simply supported beam.
*
* @author Berthold
*
*/
import java.util.ArrayList;
import java.util.List;
public class Beam {
private double length;
private List <Load> stress;
/*
* Create a beam
*/
public Beam(double length){
this.length=length;
stress=new ArrayList<Load> ();
}
/*
* Add load
*/
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);
}
/*
* Get load
*/
public Load getLoad(int atIndex){
return stress.get(atIndex);
}
/*
* Get length
*/
public double getLength(){
return length;
}
/*
* Return # of loads acting
*/
public int numberOfLoads(){
return stress.size();
}
}
This Class adds a load:
/**
* Load
*
* Load acting downwards -
* Load acting upwards +
*
* Single load: length=0
* line load: x=distance from bearing A. Length= length of line load
*
* @author Berthold
*
*/
public class Load {
public double force; // Force
public double x; // x= length from beginning of the girder to the force acting
public double length;// If not 0 => force is a line load. Starts at x, ends at x+l
/*
* Create a single force or a line load.
*/
public Load (double force,double x,double length){
this.force=force;
this.x=x;
this.length=length;
}
}
This class claculates the beams supporting forces:
/**
* Solves a simply supported beam with single and/ or line loads.
*
* Beam is not cantilevered (two bearings, one at the beginning, one at the end).
* Beam has a statically determined support configuration.
*
* Force, leading sign:
* + Force acts upwards
* - Force acts downwards
*
* Torque, leading sing
* + Clockwise
* - Anti- clockwise
*
* Bearings
* A is left, B is right
* A is pinned
* B is a roller
*
* Length
* Starts at A (0) and ends at B(l)
*
* 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
* o-------------------------------o
* A B
* |---------x1----x2---xn
* |
* |--------------- l -------------|
*
* x=0 x=l
*
* Solver calculates from left to right by solving the following equation
* (Result is resulting force at bearing A):
* Sum M=0=FA x l - F1 x (l-x1) - F2(l-x2) x ..... x Fn(l-xn)
*
* Resulting force at bearing B is calculated by solving this equation:
* Sum V=0=FA-F1-F2-....-Fn+FB
*
* @author Berthold
*
*/
public class Solve {
/*
* Get result
*/
public static Result getResults(Beam beam){
Result r=new Result();
double torqueSum=0;
double loadSum=0;
Load load;
for (int i=0;i<=beam.numberOfLoads()-1;i++){
load=beam.getLoad(i);
// Check if load is a single load
if (load.length==0){
loadSum=loadSum+load.force;
torqueSum=torqueSum+load.force*(beam.getLength()-load.x);
// Line load
} else{
double xx=(beam.getLength()-load.x)-load.length/2;
double ff=load.force*load.length;
loadSum=loadSum+ff;
torqueSum=torqueSum+loadSum*xx;
}
}
// We multiply by -1 to get the right direction of the force at the bearing.
// Remember: Per our convention - means the force points downward (globally).
// For the result - means it points in the opposite direction of the acting forces,
// so it points upwards.....
// FA=(Sum Fn x xn)/l
r.bearingA=-1*torqueSum/beam.getLength();
// FB=Sum F - FA
r.bearingB=-1*loadSum-r.bearingA;
return r;
}
}
Error handling:
/**
* BeamError
*
* Describes an error occured while creating a new beam or
* setting it's properties.
*
* @author Berthold
*
*/
public class BeamError extends Throwable{
String errorDescription;
int loadNumberCausedError;
public BeamError(String errorDescription,int loadNumberCausedError){
this.errorDescription=errorDescription;
this.loadNumberCausedError=loadNumberCausedError;
}
}
Main Class, shows how to use the package:
/**
* A simple driver
*
* Create a beam, add loads, solve.....
*
*/
public class MainBeamCalculator {
public static void main(String args){
// A girder, length=10 m
Beam myBeam=new Beam (15);
// Add some stress
try{
myBeam.addLoad(new Load(-5.5,1,0));
myBeam.addLoad(new Load(-2,4,0));
myBeam.addLoad(new Load(-3,8,0));
// Get results
System.out.println("Beam. Loads:"+myBeam.numberOfLoads());
Result r=Solve.getResults(myBeam);
System.out.println("Bearing A:"+r.bearingA+" B:"+r.bearingB);
}catch (BeamError e){
System.out.println ("Error while creating beam:"+e.errorDescription);
System.out.println("Load #"+e.loadNumberCausedError+" wrong!");
}
}
}
java physics
New contributor
1
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
1 hour 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
1 hour ago
1
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
1 hour ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
1 hour ago
add a comment |
The program uses a very simple algorithm to calculate the supporting forces of a 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 simply supported beam.
*
* @author Berthold
*
*/
import java.util.ArrayList;
import java.util.List;
public class Beam {
private double length;
private List <Load> stress;
/*
* Create a beam
*/
public Beam(double length){
this.length=length;
stress=new ArrayList<Load> ();
}
/*
* Add load
*/
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);
}
/*
* Get load
*/
public Load getLoad(int atIndex){
return stress.get(atIndex);
}
/*
* Get length
*/
public double getLength(){
return length;
}
/*
* Return # of loads acting
*/
public int numberOfLoads(){
return stress.size();
}
}
This Class adds a load:
/**
* Load
*
* Load acting downwards -
* Load acting upwards +
*
* Single load: length=0
* line load: x=distance from bearing A. Length= length of line load
*
* @author Berthold
*
*/
public class Load {
public double force; // Force
public double x; // x= length from beginning of the girder to the force acting
public double length;// If not 0 => force is a line load. Starts at x, ends at x+l
/*
* Create a single force or a line load.
*/
public Load (double force,double x,double length){
this.force=force;
this.x=x;
this.length=length;
}
}
This class claculates the beams supporting forces:
/**
* Solves a simply supported beam with single and/ or line loads.
*
* Beam is not cantilevered (two bearings, one at the beginning, one at the end).
* Beam has a statically determined support configuration.
*
* Force, leading sign:
* + Force acts upwards
* - Force acts downwards
*
* Torque, leading sing
* + Clockwise
* - Anti- clockwise
*
* Bearings
* A is left, B is right
* A is pinned
* B is a roller
*
* Length
* Starts at A (0) and ends at B(l)
*
* 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
* o-------------------------------o
* A B
* |---------x1----x2---xn
* |
* |--------------- l -------------|
*
* x=0 x=l
*
* Solver calculates from left to right by solving the following equation
* (Result is resulting force at bearing A):
* Sum M=0=FA x l - F1 x (l-x1) - F2(l-x2) x ..... x Fn(l-xn)
*
* Resulting force at bearing B is calculated by solving this equation:
* Sum V=0=FA-F1-F2-....-Fn+FB
*
* @author Berthold
*
*/
public class Solve {
/*
* Get result
*/
public static Result getResults(Beam beam){
Result r=new Result();
double torqueSum=0;
double loadSum=0;
Load load;
for (int i=0;i<=beam.numberOfLoads()-1;i++){
load=beam.getLoad(i);
// Check if load is a single load
if (load.length==0){
loadSum=loadSum+load.force;
torqueSum=torqueSum+load.force*(beam.getLength()-load.x);
// Line load
} else{
double xx=(beam.getLength()-load.x)-load.length/2;
double ff=load.force*load.length;
loadSum=loadSum+ff;
torqueSum=torqueSum+loadSum*xx;
}
}
// We multiply by -1 to get the right direction of the force at the bearing.
// Remember: Per our convention - means the force points downward (globally).
// For the result - means it points in the opposite direction of the acting forces,
// so it points upwards.....
// FA=(Sum Fn x xn)/l
r.bearingA=-1*torqueSum/beam.getLength();
// FB=Sum F - FA
r.bearingB=-1*loadSum-r.bearingA;
return r;
}
}
Error handling:
/**
* BeamError
*
* Describes an error occured while creating a new beam or
* setting it's properties.
*
* @author Berthold
*
*/
public class BeamError extends Throwable{
String errorDescription;
int loadNumberCausedError;
public BeamError(String errorDescription,int loadNumberCausedError){
this.errorDescription=errorDescription;
this.loadNumberCausedError=loadNumberCausedError;
}
}
Main Class, shows how to use the package:
/**
* A simple driver
*
* Create a beam, add loads, solve.....
*
*/
public class MainBeamCalculator {
public static void main(String args){
// A girder, length=10 m
Beam myBeam=new Beam (15);
// Add some stress
try{
myBeam.addLoad(new Load(-5.5,1,0));
myBeam.addLoad(new Load(-2,4,0));
myBeam.addLoad(new Load(-3,8,0));
// Get results
System.out.println("Beam. Loads:"+myBeam.numberOfLoads());
Result r=Solve.getResults(myBeam);
System.out.println("Bearing A:"+r.bearingA+" B:"+r.bearingB);
}catch (BeamError e){
System.out.println ("Error while creating beam:"+e.errorDescription);
System.out.println("Load #"+e.loadNumberCausedError+" wrong!");
}
}
}
java physics
New contributor
The program uses a very simple algorithm to calculate the supporting forces of a 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 simply supported beam.
*
* @author Berthold
*
*/
import java.util.ArrayList;
import java.util.List;
public class Beam {
private double length;
private List <Load> stress;
/*
* Create a beam
*/
public Beam(double length){
this.length=length;
stress=new ArrayList<Load> ();
}
/*
* Add load
*/
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);
}
/*
* Get load
*/
public Load getLoad(int atIndex){
return stress.get(atIndex);
}
/*
* Get length
*/
public double getLength(){
return length;
}
/*
* Return # of loads acting
*/
public int numberOfLoads(){
return stress.size();
}
}
This Class adds a load:
/**
* Load
*
* Load acting downwards -
* Load acting upwards +
*
* Single load: length=0
* line load: x=distance from bearing A. Length= length of line load
*
* @author Berthold
*
*/
public class Load {
public double force; // Force
public double x; // x= length from beginning of the girder to the force acting
public double length;// If not 0 => force is a line load. Starts at x, ends at x+l
/*
* Create a single force or a line load.
*/
public Load (double force,double x,double length){
this.force=force;
this.x=x;
this.length=length;
}
}
This class claculates the beams supporting forces:
/**
* Solves a simply supported beam with single and/ or line loads.
*
* Beam is not cantilevered (two bearings, one at the beginning, one at the end).
* Beam has a statically determined support configuration.
*
* Force, leading sign:
* + Force acts upwards
* - Force acts downwards
*
* Torque, leading sing
* + Clockwise
* - Anti- clockwise
*
* Bearings
* A is left, B is right
* A is pinned
* B is a roller
*
* Length
* Starts at A (0) and ends at B(l)
*
* 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
* o-------------------------------o
* A B
* |---------x1----x2---xn
* |
* |--------------- l -------------|
*
* x=0 x=l
*
* Solver calculates from left to right by solving the following equation
* (Result is resulting force at bearing A):
* Sum M=0=FA x l - F1 x (l-x1) - F2(l-x2) x ..... x Fn(l-xn)
*
* Resulting force at bearing B is calculated by solving this equation:
* Sum V=0=FA-F1-F2-....-Fn+FB
*
* @author Berthold
*
*/
public class Solve {
/*
* Get result
*/
public static Result getResults(Beam beam){
Result r=new Result();
double torqueSum=0;
double loadSum=0;
Load load;
for (int i=0;i<=beam.numberOfLoads()-1;i++){
load=beam.getLoad(i);
// Check if load is a single load
if (load.length==0){
loadSum=loadSum+load.force;
torqueSum=torqueSum+load.force*(beam.getLength()-load.x);
// Line load
} else{
double xx=(beam.getLength()-load.x)-load.length/2;
double ff=load.force*load.length;
loadSum=loadSum+ff;
torqueSum=torqueSum+loadSum*xx;
}
}
// We multiply by -1 to get the right direction of the force at the bearing.
// Remember: Per our convention - means the force points downward (globally).
// For the result - means it points in the opposite direction of the acting forces,
// so it points upwards.....
// FA=(Sum Fn x xn)/l
r.bearingA=-1*torqueSum/beam.getLength();
// FB=Sum F - FA
r.bearingB=-1*loadSum-r.bearingA;
return r;
}
}
Error handling:
/**
* BeamError
*
* Describes an error occured while creating a new beam or
* setting it's properties.
*
* @author Berthold
*
*/
public class BeamError extends Throwable{
String errorDescription;
int loadNumberCausedError;
public BeamError(String errorDescription,int loadNumberCausedError){
this.errorDescription=errorDescription;
this.loadNumberCausedError=loadNumberCausedError;
}
}
Main Class, shows how to use the package:
/**
* A simple driver
*
* Create a beam, add loads, solve.....
*
*/
public class MainBeamCalculator {
public static void main(String args){
// A girder, length=10 m
Beam myBeam=new Beam (15);
// Add some stress
try{
myBeam.addLoad(new Load(-5.5,1,0));
myBeam.addLoad(new Load(-2,4,0));
myBeam.addLoad(new Load(-3,8,0));
// Get results
System.out.println("Beam. Loads:"+myBeam.numberOfLoads());
Result r=Solve.getResults(myBeam);
System.out.println("Bearing A:"+r.bearingA+" B:"+r.bearingB);
}catch (BeamError e){
System.out.println ("Error while creating beam:"+e.errorDescription);
System.out.println("Load #"+e.loadNumberCausedError+" wrong!");
}
}
}
java physics
java physics
New contributor
New contributor
edited 24 mins ago
200_success
128k15150412
128k15150412
New contributor
asked Dec 23 at 20:46
Berthold Fritz
113
113
New contributor
New contributor
1
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
1 hour 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
1 hour ago
1
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
1 hour ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
1 hour ago
add a comment |
1
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
1 hour 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
1 hour ago
1
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
1 hour ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
1 hour ago
1
1
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
1 hour ago
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
1 hour 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
1 hour 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
1 hour ago
1
1
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
1 hour 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
1 hour ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
1 hour ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
1 hour 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
1 hour 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-a-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
1 hour 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
1 hour 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 1 hour ago
answered 2 days ago
Timothy Truckle
4,838416
4,838416
Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly.
– Berthold Fritz
1 hour 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
1 hour ago
Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly.
– Berthold Fritz
1 hour ago
Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly.
– Berthold Fritz
1 hour 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-a-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
1
You should not change the question based on the reviews. This may confuse future readers....
– Timothy Truckle
1 hour 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
1 hour ago
1
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
1 hour ago
Thank you! Geting the hang of it :-)
– Berthold Fritz
1 hour ago