Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 7. Working with Protocols > Favoring Composition Over Inheritance

7.1. Favoring Composition Over Inheritance

An object oriented design axiom known as "favor composition over inheritance" means that rather than always turning to inheritance as a tool for extending functionality of a given class, you should instead first try to solve the problem by using other classes compositionally within your class. For example, if you needed to implement a class that provided an interface between a network service and your application, instead of inheriting from a socket class (a class that gives you access to network resources), you should include another object in your class, which provides that network connectivity. You should "compose" your design from other reusable components. Building your designs in this way results in more flexibility, because those bits and pieces that you are composing together to solve a given problem can later be swapped out and changed to solve another problem. This is an incredibly powerful design philosophy and one which you should strive for in your code.

It is certainly possible to follow this design philosophy simply by using standard object oriented techniques. However, designing components for reuse causes complications.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial