I favor composition over inheritance

Many developers learn object oriented programming in college, and a favorite topic of teachers seems to be inheritance. Abstract classes, virtual methods, and overriding are neat concepts that easily can be used to compare audience: only good programmers understand all those well.

But the same good programmers, especially in their junior period, often think that inheritance is also neat in practice, since they have learned about it from a good teacher!

However, in real life projects, I personally found inheritance introducing multiple issues that could have been easily avoided or overcame if composition pattern was chosen instead. Although we say a student is a person, we can convert this to a similarly logical sentence: a student record has a person record!

Some problems that can be avoided this way are:

  • In many programming languages (e.g. C#) you can only inherit from one class, not more. If the student also needed to inherit from a base class other than person, for any reason (e.g. entity base class to support some common logic from a special, already existing, framework), you couldn’t inherit from person class at all.
  • Sometimes inheritance seems correctly implemented but Liskov’s substitution principle fails at runtime.
  • You cannot compare student and other objects that have the same person base class, such as a teacher, to detect if they actually refer to the same person. If both student and teacher classes inherit from person base, you cannot have the same person instantiated as both a student object and a teacher object without losing comparability (unless you override equality, at least). To resolve this with composition you can simply compare the references of the person record referred by the student record with that referred by the teacher records.

See also the Benefits and Drawbacks sections of the Wikipedia article that I’ve found on this topic.

PS: If you really think inheritance is good in your specific case, do it. But think about extracting the core logic of the base class in a separate class that can be used inside a composition relation, too. In this case it will be something like the diagram below:

{ BaseClass --uses--> CoreService }
and
{
  { InheritingClientClass --inherits--> BaseClass }
  or
  { OtherClientClass --uses--> CoreService }
}
Advertisements

About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in Architecture and tagged , . Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s