O'Reilly logo

Refactoring with Microsoft Visual Studio 2010 by Peter Ritchie

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Composition over inheritance

After seeing some of the issues that arise from not correctly using inheritance, the next logical step is to look at a principle that avoids inheritance altogether. This principle is the Prefer Composition over Inheritance principle.

Composition over Inheritance means that classes should be composed of instances of other classes to implement behavior or attributes instead of inheriting behavior or attributes from a base class. This means that a class would contain one or more fields that are references to other classes, and the current class delegates work to them.

Let's look at a slightly different design for Invoice. An invoice could be considered simply as a collection of InvoiceLineItems. As such, we could implement ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required