Tuesday, April 03, 2012

Favor Composition to Inheritance

As we all know Java is an Object-Oriented Programming Language. OOP was developed in first place to increase code reuse and maintainability.

The Myth

Programmers introduced to OOP Language(s) have a mindset that code reuse can be achieved only by Inheritance (extends) in Java. But are not aware of the alternatives even if they came across them.

For Example:

List<Car> carRef = new ArrayList<Car>();  //Generic List of Car References

Q.  Why Inheritance is considered bad?

A.  Experienced Programmers are aware of the fact and even the Design Patterns states the same using Inheritance across boundaries are considered bad as author of that library may change the internal implementation details which might break our abstraction that depends on it blowing up the whole stack.


Better Alternative - Prefer Composition to Inheritance




-------------------------
I will soon add more on this. Please do post your comments if your thinking differs from me. I will try to incorporate you questions/suggestion here so everyone has a better idea on this concept.


Hope this Helps! Please write your comments it will help me improve.