I have a class Installment
and a method executeTransaction
. The field totalBalance
represents the difference between total due and total paid. Inside method executeTransaction
the installment object is modified using setters. And after every setter the updateTotalBalance is called.
public class Installment {
private BigDecimal principalDue;
private BigDecimal principalPaid;
private BigDecimal interestDue;
private BigDecimal interestPaid;
private BigDecimal feeDue;
private BigDecimal feePaid;
private BigDecimal penaltyDue;
private BigDecimal penaltyPaid;
private BigDecimal totalBalance;
public void updateTotalBalance() {
this.totalBalance = this.principalDue.subtract(this.penaltyPaid)
.add(this.interestDue).subtract(this.interestPaid)
.add(this.feeDue).subtract(this.feePaid)
.add(this.penaltyDue).subtract(this.penaltyPaid);
}
//seters
//getters
}
Transaction method:
public void executeTransaction(Installment installment){
//code
installment.setPrincipalPaid(bigDecimalValue);
installment.updateTotalBalance();
//code
installment.setPenaltyDue(bigDecimalValue);
installment.updateTotalBalance();
}
I was thinking about putting the updateTotalBalance
inside the setters, but for me both of these approaches seem contradictory with the best design principles.
Q: I want to know if there are better solutions to update a field in a class when others fields are modified.