Search code examples
design-patternsdatabase-designmodeluml

Modeling bank account balance


I created a class model for banks that has a class BankAccount with an attribute (property) balance (among others). Also a Transaction class, associated with BankAccount, that stores each account transaction. After storing a transaction I always update the balance.

One of the developers that work in my company said me that having a balance attribute is not a good idea, but refused to explain why. He said it is obvious. I can't see any obvious mistake.

Calculating the balance every time I need it by processing all transactions doesn't seem smart. Am I missing something?


Solution

  • Every time you add, remove, or modify a Transaction you must recalculate the balance. And there's a high likelihood one of those things will happen in code written by someone else who doesn't know or forgot about the balance. Your developer has probably been burned this way many times. To them, the cost of recalculating the balance every time someone wants to look at it is minute compared to the cost and embarrasment of a balance that is wrong. Recalculating also reduces and simplifies the program--always a good thing.

    Generally speaking, computer time--CPU and disk and everything else--is cheap. Spend if freely to improve reliability and save on programmer time.

    Now if you have a program that needs 200ms to sum up the transactions, and that program gets 10,000 queries on the balance every second, your approach starts to make sense.