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 ...
Get JavaScript Patterns now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.