开发者

Usage of Generalization over Aggregation

I have this class model where, Bank is a class which is now going for computerized Banking network. This must have ATM(Automatic Teller Machine) and also Human Cashier.

I used Genera开发者_JAVA百科lization and have taken a class called AccountHandlers which inherits Bank class. This AccountHandlers further have ATM and HumanCashier aggregated to it.

Now the thing is, my friend was arguing that i have taken the whole thing wrong. According to him AccountHandlers must be aggregated to Bank and that ATM and HumanCashier must inherit to AccountHandlers.

I am a bit confused over it. How can i model it!! or is that both method correct?


I would go back to the basics.

You should ask yourself if an ATM is an AccountHandler, or if an AccountHandler has an ATM. That should give you a general answer as to the question of using inheritance or composition.

Both would be correct. Only one would be a good design and that is dependent on what your application is trying to do.

Generally, there is a rule of thumb (taken from Effective Java) that states that you should favor composition over inheritance. Take that with a grain of salt, and make sure you are designing your app the right way. (For more info see Prefer composition over inheritance?)


Typically inheritance (or specialization) is used to model a "is-a" relation, while aggregation/composition is used for "has-a" relations.

Now you can ask yourself which one is correct:

  • an account handler is a bank or a bank has one or more account handlers
  • human cashier is a (special kind of) account handler or account handler has a human cashier

In my opinion the bold statements are correct. So you should use aggregation or composition for bank->account handlers and inheritance for account handler->human cashier.


If it works it's correct. Don't get caught up on the waste-of-time that is UML modelling. Write a prototype and any design flaws will soon become apparent.


Please talk to your domain experts and get the model validated from them. I think this is where the first few chapters in Domain Driven Design help. You should try to define the entities and their relationships (has or is a), draw them on a white board and discuss them with your domain experts.

Despite whatever you do please write unit tests around your implementation. Because with such confusions you are likely to modify the class structure and at that time your unit tests will ensure that you can smoothly re-factor the code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜