Thursday, January 6, 2011

Favor object Composition over Class Inheritance

Happy New Year, a warm welcome in 2011.

Today we will see Composition vs Inheritance.

Object composition and inheritance are two techniques for reusing functionality in object-oriented systems. Inheritance is often called white-box reuse.

Object composition is a different method of reusing functionality. Objects are composed to achieve more complex functionality. This approach requires that the objects have well-defined interfaces since the internals of the objects are unknown. Because objects are treated only as "black boxes," this type of reuse is often called black-box reuse.

The advantage of class inheritance is that it is done statically at compile-time and is easy to use and disadvantages are that derived class becomes dependent on parent implementation and inheritance breaks encapsulation. Also, implementation/functionality inherited from parent class cannot be changed at runtime.

In object composition, functionality is acquired dynamically at run-time by object reference to other objects. The advantage of composition is that implementation can be replaced at run-time. It is providing encapsulation. It is independent and loosely coupled with child classes.

The disadvantage of composition is that the behavior of the system may be harder to understand just by looking at the source code. A system using object composition may be very dynamic in nature so it may require running the system to get a deeper understanding of how the different objects cooperate.



                           Inheritance                                        Composition

class Engine { }                                               class Engine { }

class Car : Engine                                          class Car : Engine
{                                                                     {
    //Do code                                                           Engine carEngine;   
}                                                                     }




How ever it is not necessary that you always use composition. There are scenarios where we have to use inheritance to create related objects; especially when we want to restrict object creation of Master Class. We can create Abstract Base class to achieve this.

No comments:

Post a Comment