Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inheritance vs. composition for testability

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?

like image 425
Parag Avatar asked Apr 17 '09 13:04

Parag


People also ask

What is better inheritance or composition?

Composition offers better test-ability of a class than Inheritance. If one class consists of another class, you can easily construct a Mock Object representing a composed class for the sake of testing.

When would you use composition instead of inheritance?

Composition allows to test the implementation of the classes we are using independent of parent or child class. 4. Inheritance cannot extend final class. Whereas composition allows code reuse even from final classes.

Why do we choose composition over inheritance?

One more benefit of composition over inheritance is testing scope. Unit testing is easy in composition because we know what all methods we are using from another class. We can mock it up for testing whereas in inheritance we depend heavily on superclass and don't know what all methods of superclass will be used.

Why do we prefer composition more than inheritance in object-oriented design?

To favor composition over inheritance is a design principle that gives the design higher flexibility. It is more natural to build business-domain classes out of various components than trying to find commonality between them and creating a family tree.


1 Answers

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).

like image 135
TheTXI Avatar answered Sep 27 '22 19:09

TheTXI