inheritance vs. composition for testability

Parag picture Parag · Apr 17, 2009 · Viewed 8k times · Source

While designing my objects I find composition to be a better choice from the perspective of testability. The reason being, I can mock parts of the composition structure if I need to, while running unit tests. This is not possible if I have an inheritance hierarchy.

I would like to know if others have also found this to be a reason to prefer composition. Also what other testability pitfalls did you get into because inheritance was used?

Answer

TheTXI picture TheTXI · Apr 17, 2009

I believe that the more you start to develop using design patterns, you'll find more and more often where composition is going to be favored over inheritance. I actually believe in the Head First: Design Patterns book that "Favor Composition Over Inheritance" is one of the primary design principles.

Your example of being able to mock up parts of the composition for testing is probably one of the best examples possible.

Edit: Although the basic principle in design patterns is to favor composition over inheritance, that doesn't mean that there aren't design patterns which utilize inheritance where it is needed. Another basic example is the decorator pattern, where you are coding towards an abstract superclass (although this is for type matching and not for implementing an "is-a" relationship).