Favor composition over inheritance

From CSSEMediaWiki
Revision as of 01:31, 4 October 2008 by Elliot Fisher (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The idea behind this is that having a composition relationship gives less coupling than an inheritance relationship, and increased flexibility.

If you can achieve what you need by a composition relationship then do it that way. When you have a subclass which overrides a method of the superclass, it needs to make assumptions about the state of that superclass when the method is called. It is simpler to "plug-in" behaviour of another class. Think of composition as inheriting only a small interface of the other class, whereas with inheritance you inherit the entire interface. The increased flexibility is achieved because the smaller objects that are contained in the container object can be re-used in various contexts, while adding behaviour to the container class.

A good example of this in practice is the Strategy pattern.

See also

Personal tools