Lets say I have following class:
public class RectangularPrism{
public Integer width;
public Integer height;
public Integer depth;
//setters and getters
}
I use it for calculate sum of volume of all prisms. I have two methods to calculate this. Which one is better?
This one use conditional operator.
public Integer volumeSum(List<RectangularPrism> prismList){
Integer sum = 0;
for(RectangularPrism prism: prismList){
Integer width = prism.getWidth() == null ? 0 : prism.getWidth();
Integer height = prism.getHeight() == null ? 0 : prism.getHeight();
Integer depth = prism.getDepth() == null ? 0 : prism.getDepth();
sum += width * height * depth;
}
return sum;
}
This one use try catch block
public Integer volumeSum(List<RectangularPrism> prismList){
Integer sum;
for(RectangularPrism prism: prismList){
try {
Integer width = prism.getWidth();
Integer height = prism.getHeight();
Integer depth = prism.getDepth();
sum += width * height * depth;
}catch( NullPointerException e){}
}
return sum;
}
Which one would be better If my class would have 100 or more fields which determine result?
Is it fine to use try catch to handle null values?