Let's get a simple example:
Class Foo{
private BigDecimal item1;
private BigDecimal item2;
private BigDecimal item3;
private BigDecimal item4;
private BigDecimal item5;
//setters and getters
public BigDecimal getTotal(){
BigDecimal total = BigDecimal.ZERO;
if(null != item1){
total =total .add(item1);
}
if(null != item2){
total =total .add(item2);
}
...
...
}
}
I am summing in entity level. this is correct way or not?
can any one give me better code for getting total Value
Use a List<BigDecimal>
public BigDecimal getTotal(){
List<BigDecimal> values = Arrays.asList(item1, item2, item3, item4, item5)
BigDecimal total = BigDecimal.ZERO;
for (BigDecimal value : values) {
if(value != null) {
total = total.add(value);
}
}
return total;
}
You can use a loop to make your code simple :
import java.util.Arrays;
...
public BigDecimal getTotal(){
BigDecimal total = BigDecimal.ZERO;
for(BigDecimal bd: Arrays.asList(item1,item2,item3,item4,item5)){
if(null != bd){
total =total .add(bd);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With