Abstract from Design patterns : Elements of Reusable Object-Oriented Software
1 Program to interface, not an implementation.
- Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the interface that client expect.
- Clients remain unaware of the classes that implement these objects. Clients only know about the abstract class defining the interface.
2 Favor object composition over class inheritance.
Despite of obvious situation we should apply class inheritance or objects composition, I discuss the situations that two methods are both practicable.
Advantages of Inheritance
Straightforward to use.
It is easy to modify the implementation of subclasses.
Disadvantages of Inheritance
Breaking the “Encapsulation”
Forcing the implementations of subclass change when implementations of parent class change, which making reusing subclasses difficult considering the changes of their parent class.
Advantages of Composition
- Maintaining the “Encapsulation”
Objects don’t know the implementation of others and they can deal with others’ interfaces. As a result, there is fewer implementation dependency.
2. Class hierarchies remain small
To accomplish a functionality, composition take advantages of manipulating relationships and collaborations of several objects, which keep the scale of a class small and focused on a few functionality.
Disadvantages of Composition
Requirement of careful design avoiding accomplishing a functionality with too many objects.