Favor composition over inheritance
JaninaVoigt (Talk | contribs) (→See also) |
|||
Line 1: | Line 1: | ||
− | + | Composition should be used when possible because composition minimizes coupling, and therefore increases flexibility. | |
− | If you can achieve what you need by a composition relationship then do it that way. When | + | If you can achieve what you need by a composition relationship then do it that way. Inheritance should only be used when necessary, or when the benefits of inheritance can be fully utilized. |
+ | |||
+ | When a class overrides a method of its super-class, it needs to make assumptions about the state of that super-class when the method is called. It is simpler to "plug-in" the behaviour of another class via a composition relationship. Think of composition as inheriting only a small part of interface of another class, whereas inheritance forces you to inherit the entire interface. Flexibility is increased because following this rule should result in a greater number of smaller objects which can be interchanged and reused in various contexts. | ||
A good example of this in practice is the [[Strategy]] pattern. | A good example of this in practice is the [[Strategy]] pattern. |
Revision as of 02:57, 27 July 2009
Composition should be used when possible because composition minimizes coupling, and therefore increases flexibility.
If you can achieve what you need by a composition relationship then do it that way. Inheritance should only be used when necessary, or when the benefits of inheritance can be fully utilized.
When a class overrides a method of its super-class, it needs to make assumptions about the state of that super-class when the method is called. It is simpler to "plug-in" the behaviour of another class via a composition relationship. Think of composition as inheriting only a small part of interface of another class, whereas inheritance forces you to inherit the entire interface. Flexibility is increased because following this rule should result in a greater number of smaller objects which can be interchanged and reused in various contexts.
A good example of this in practice is the Strategy pattern.