Cover by Stoyan Stefanov

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Chapter 6. Code Reuse Patterns

Code reuse is an important and interesting topic simply because it’s natural to strive for writing as little and reusing as much as possible from existing code, which you or someone else has already written. Especially if it’s good, tested, maintainable, extensible, and documented code.

When talking about code reuse, the first thing that comes to mind is inheritance, and a great deal of the chapter is dedicated to this topic. You see several ways to do “classical” and nonclassical inheritance. But it’s important to keep the end goal in mind—we want to reuse code. Inheritance is one way (means) for us to reach that goal. And it’s not the only way. You see how you can compose objects from other objects, how to use object mix-ins, and how you can borrow and reuse only the functionality you need without technically inheriting anything permanently.

When approaching a code reuse task, keep in mind the advice the Gang of Four book has to offer on object creation: “Prefer object composition to class inheritance.”

Classical Versus Modern Inheritance Patterns

Often you hear the term “classical inheritance” in discussions on the topic of inheritance in JavaScript, so let’s first clarify what classical means. The term is not used in the sense of something antique, settled, or widely accepted as the proper way of doing things. The term is just a play on the word “class.”

Many programming languages have the notion of classes as blueprints for objects. In those languages ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required