I've asked myself this question a number of times when creating classes, particularly those involving collections, but I've never come up with a satisfactory answer. It's a OOP design question.
For example, in a checkbook register program say I have a class of BankAccount
. BankAccounts contain data involving the Name of the account, the Type of account (enum of Checking, Saving,...), and other data, but most importantly is a collection of the Adjustment
s (deposits or withdrawals) in the account.
Here, I have two options for keeping a collection of the Adjustments:
I think both solutions are intuitive, and, of course, both offer some advantages and disadvantages. For example, instantiating allows the class (in languages that allow only a single base class) to inherit from another class, while inheriting from collection makes it easy to control the Add, Remove, and other methods without having to write surrogate methods to 'wrap' those.
So, in such situations, which is a better approach?
To me, a bank account has a collection of adjustments. A bank account is not a collection of adjustments, because it "is" much more than that: it also "is" a name and a type, etc.
So, in your case (and similar cases), I suggest you aggregate a collection inside your class.
In case of doubt, avoid inheritance. :-)
I can argument this further. In order to use inheritance properly, the subclass must satisfy Liskov's substitution principle; this means that, in your case, BankAccount
should be a valid type anywhere a Collection
is expected. I don't think that's the case, because a Collection
probably exposes methods such as Add()
and Remove()
, whereas you will want to exert some control over adding and removing adjustments from your bank account rather than letting people add and remove them freely.
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