Association VS inheritance. Which one you will choose?

Whenever there is a new requirement, or say functional change in your software system. Which has some behavior changes in your software. We achieve it through association or inheritance. There is no doubt that both have their own importance in design. But the question is, "Which one to choose?"


 Simple rule to pick one is –

“If the cost of association is less than the cost of inheritance, then use association and vice versa.”

OR

“If new change is permanent and part of the core behavior of the existing system, then use inheritance, otherwise, use association.”


Inheritance comes with a liability. As you have to increase your structure to accommodate some behavioral requirement. That structure will be part of your object always. Doesn’t matter if you are using it, or not using it; all the time, it will be part of your class. 


For example – Banking and other industries have their own IT services. As all world has moved to IT. It is a permanent change to have your own IT infrastructure to facilitate your services. It is not a good idea to associate (or outsource) your core business implementation. Though it is the computer science department not belongs to core banking and finance. But it is a permanent change to banking services, so good to enhance the current structure. That is called inheritance.



Association doesn’t have any liability. It is a usage relationship. It is different from composition and aggregation. Whenever you have particular requirements, where you use services from another system on-demand basis. Whenever you feel there is no more requirement for service, don’t use it. No burden at all. 


For example In all IT companies we need cab service. For which they have local cab vendors. Here they use association rule. As per the rule, running cab services is not the core behavior of an IT company. They will not use it all the time. Only on start and end shifts timing. So, why to add our own cab service to the organization. As it will come with a liability. Also comes with huge maintenance cost and other associated cost. 


Conclusion -

Most of the time, we use association rule. You can see it around you - that's why we have growing service industries around us. Likewise, in our class design also. We use association rules. We don’t put (or enhance) class structure until and unless new behavior change actually belongs to existing class's core behavior, and it is a permanent change.



Thanks for reading it. To learn more about design patterns and basic design principles, please see my web page.

Comments

Popular posts from this blog

Non-virtual interface idiom (NVI)

Factory method design pattern for beginners.

Architectural patterns => Mud to structure => layers.