Kevin Greer's Stuff
[ start | index | login ]
start > 2006-10-17 > 1

2006-10-17 #1

Created by kgr. Last edited by kgr, one year and 281 days ago. Viewed 243 times. #1
[edit] [rdf]
labels
attachments

Favour What over What?

Favour composition over inheritance.

All learned OO practitioners will tell you the same thing. But why? The reason is that dynamic composition offers better code reuse (and therefore, better productivity) than static inheritance.

Consider that I have an Interface ‘Abc’ and that I have a few implementations: ‘SimpleAbc’, ‘DefaultAbc’, ‘CompoundAbc’, ‘MockAbc’, ‘SuperSpecialAbc’, etc.

Now consider the following ways that I might want to add additional behaviour to implements of Abc:

  • synchronization
  • logging
  • caching
  • authentication
  • filtering (of some collection based return values)
  • read-only support
  • sorting (of some collection based return values)
  • etc.
With inheritance you would need 1024 classes to implement all combinations: 2^7 features * 5 implementations.

With composition you would only need 12 classes: 5 implementations + 7 decorators.

It is very unlikely that you would ever need all 1024 combinations, but it is very likely that you would need more than 12.

Dynamic composition literally gives exponentially better code reuse than static inheritance. They say that some "super-programmers" are ten times faster than the average but mastering composition lets you become O(x^n) faster; which is usually much(^n) better than being a mere "ten times" faster.

Of course this isn’t really true in a general sense. It is only true in languages like Java where inheritance is static. In languages with dynamic inheritance, inheritance is just as good.

This leads me to conclude that the maxim:

Favour Composition over Inheritance

could be written more accurately as:

Favour dynamic composition over static inheritance.

or, more generally, as just:

Favour dynamic over static.

no comments | post comment
peerbox.com | Copyright 2005-2006 Kevin G. R. Greer