Quote:Original post by chairthrower
The authors of the GoF book, design patterns famously state, “prefer composition over inheritance”. however it never seems to be noted ( at least its difficult to simply reconcile) that this flies in the face of 2 of the 4 most commonly cited attributes of OO design - namely polymorphism, and inheritance ( along with encapsulation and modularity).
AFAIK, the GoF make that statement to discourage the over-use of inheritance when it is not actually required (hence the use of the soft wording "prefer").
Inheritance is used to model the "is a" relationship between two entities (and to enable polymorphism).
If you don't explicitly need an "is a" relationship, then you also don't need polymorphism *in that particular case*, which means that inheritance is the wrong tool *in that particular case*.
For example, lets say we're writing a queue class, which we want to implement by reusing the existing std::vector class. We can do this either by composition or by inheritance.
Both of these approaches work, so they are both "right". However, one uses a model where the "queue is a vector", which is obviously incorrect ("bad") as the queue does not contain all of the functionality which a vector has.
//Using inheritance: "bad and right"template<class T>class MyQueue : private std::vector<T>{public: void push( const T& in ) { push_back(o); } bool pop( T& out ) { if( empty() ) return false; out = front(); pop_front(); return true; }};//Using composition: "good and right"template<class T>class MyQueue{public: void push( const T& in ) { data.push_back(o); } bool pop( T& out ) { if( data.empty() ) return false; out = data.front(); data.pop_front(); return true; }private: std::vector<T> data;};
Quote:Maybe the gof book is merely an extremely well disguised and covert attack on OO theory - i dont know. i guess i feel that with basic contradictions like this, it is really hard to make generalisations about what might be considered good oo design or how to go about learning what would be called 'best practice'.
It's not a contradiction, just generalised advice. It's only contradictory if you misinterpret it to mean that you shouldn't use inheritance ever (instead of meaning that you should only use inheritance when it is actually useful).