'Modeling bank account balance [duplicate]
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 1:[1]
Personally whenever I want to gain access to an objects variables
, I always make use of properties
, even if it is only the getter
that is public
.
The getter
is not always simply return foo
, sometimes you will want to initialise other objects
or perform logging. Similarly the setter
provides a neat mechanism for validating
the new value
attempting to be assigned to the variable
.
OK both of these examples can be performed prior to directly accessing the variable
, but if you're accessing it frequently you don't want to be writing object initialisation
and validation
code every time. Having it in one centralised place is far more convenient and it fits encapsulation.
I would suggest you ask your colleague, again, why he thinks it is a bad idea. He should have no reservations about explaining his reasoning.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |