Pages

Subscribe:

Ads 468x60px

Labels

Sunday, November 7, 2010

Inheritance – is not the way to achieve code reuse



What is Inheritance for? 



When I ask this question, invariably I get this precooked answer “Inheritance is the way to achieve code re-usability

No its NOT !


Inheritance is a mechanism used to achieve the categorization and facilitate polymorphism.

Using Inheritance, you can build the hierarchy of same type of entities separated in its own characteristics. By doing this you can efficiently use another OOP concept “Polymorphism” which allows the same control to manage all the entities in a same type even if they are different in their implementation.

This is the main driver for using inheritance in the design of a software system. Not code reuse.

Rule of thumb: While designing the Inheritance designer/developer should confirm that, "is a" relationship between sub-class & its super-class.
In some point (special case scenario) this relationship can be overruled.
ex: 'Student is a Person' & 'Employee' is a Person'. So Person can be the Base class for Student and Employee.

Incidental Code Reuse due to Inheritance

There is some code reuse associated with inheritance:
  • Derived classes can (if desired) reuse code from the super-class hierarchy
  • Control code taking advantage of polymorphism is reused for every class in a category
But this is not the reason to use inheritance. The reasons for using inheritance are modularity, separation of concerns, clear representation of concepts, categorization and polymorphism.

How to achieve the code reuse ?


A better way for achieving code reuse is Composition!!!

Inheritance Over Composition
    Inheritance          
 
      -  House is a Building
      -  Temple is a Building


   Composition

     -  House has BedRooms
     -  House has Visitors
     -  Temple has Visitors











Inheritance Over Composition (better way to code reuse): Here, as per the example, you can re-use Bedroom & visitor classes wherever you want.

(Instead of keeping Bedroom and Visitors as separate classes, if you declare the same in Building, you cannot achieve the taste of whole re-usability and the re-usability level is limited to the Building type subclasses.)

No comments:

Post a Comment