# update field when others fields are motifed [closed]

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)
}

//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.

## closed as off-topic by πάντα ῥεῖ, Mast, Toby Speight, AlexV, mdfst13Oct 4 at 13:28

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "Code not implemented or not working as intended: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review." – πάντα ῥεῖ, mdfst13
If this question can be reworded to fit the rules in the help center, please edit the question.

• May be the Observer design pattern would be a more generic and flexible solution for that problem. – πάντα ῥεῖ Oct 4 at 9:42
• If it's not clear, the problem with this post is that it doesn't actually update the total balance when other fields are modified. It updates when execute transaction is run. So it does not actually accomplish the task that you say you're attempting. You've also elided out all the context, so we can't suggest changes outside the code that you've posted. This is required on Stack Overflow but is a close reason here. Code here should be specific, not general. – mdfst13 Oct 4 at 13:34

The simplest solution would be to drop the totalBalance field and simply have getTotalBalance calculate the value:

public BigDecimal getTotalBalance() {
return this.principalDue.subtract(this.penaltyPaid)