Hello! Welcome to the first lesson in our new module, "Compositional Patterns: Mixins and Traits."
In the previous module, we delved deep into ES6 classes, culminating in a lesson on extending built-in objects like Array and Error. We saw how inheritance, using the extends keyword, is a powerful tool for code reuse and specialization. However, while inheritance is a fundamental concept in object-oriented programming, it's not always the best tool for the job. Over-reliance on it can lead to rigid and fragile designs.
Today, our goal is to analyze the trade-offs between inheritance and composition for a given design scenario. We'll explore why the famous software design principle "favor composition over inheritance" exists, and you'll learn the critical thinking framework to decide which pattern is appropriate for the problems you face.
The Two Pillars of Code Reuse: Inheritance vs. Composition
At their core, both inheritance and composition are patterns that help you reuse code.
- Inheritance models an "IS-A" relationship. A
Manageris anEmployee. APNGImageis anImage. The subclass inherits properties and methods directly from the superclass, forming a tight, hierarchical bond. - Composition models a "HAS-A" relationship. A
Carhas anEngine. AnEmployeehas aPersonrecord. A complex object is built by assembling, or composing, other, smaller objects.
This visual comparison illustrates the structural difference:

Inheritance often seems intuitive at first, but let's explore scenarios where this intuition can lead us astray.
When Inheritance Creates Problems
Inheritance works well when you have a stable, linear hierarchy. However, software is rarely stable, and requirements often evolve in ways that don't fit neatly into a pre-defined tree structure.
Let's watch two short video segments that illustrate this common problem.
Composition Vs Inheritance - Why You Should Stop Using Inheritance
The first video, from Web Dev Simplified, uses a great example from game development. It shows how an inheritance-based design for game monsters quickly becomes unmanageable when you need to combine abilities.
Please watch from 01:21 to 04:04. Pay close attention to the initial setup with Monster, FlyingMonster, and SwimmingMonster. The key moment is when the presenter tries to create a FlyingSwimmingMonster and reveals the core weakness of this inheritance model.
This second video, from CodeAesthetic, demonstrates the same issue in a different context: an image processing library. This will help solidify your understanding of the problem's nature.
Now, watch from 00:28 to 03:28. Notice how the initial design using an Image superclass seems logical, but breaks down when a DrawableImage is introduced—a type of image that doesn't need file-loading methods. This highlights the rigidity of inheritance.
These examples expose several critical disadvantages of implementation inheritance:
- Tight Coupling: The subclass is tightly coupled to the superclass's implementation. A change in the parent (like removing the
loadmethod in theImageexample) can ripple down and break child classes. This is often called the fragile base class problem. - Rigidity: Inheritance hierarchies are defined statically. You can't easily create new combinations of behaviors at runtime. As seen with the monsters, you'd need a separate class for every possible combination (
FlyingPoisonousMonster,SwimmingArmoredMonster, etc.), leading to a combinatorial explosion of classes. - Encapsulation Leakage: Inheritance can sometimes break encapsulation. Subclasses often have access to
protectedmembers of the parent, creating a dependency on implementation details that should ideally be hidden.
The Flexible Alternative: Composition in Action
Composition solves these problems by decoupling behaviors from a rigid hierarchy. Instead of a class being something, it has a collection of capabilities.

Let's see how the problems from the videos are solved using composition.
Composition Vs Inheritance - Why You Should Stop Using Inheritance
First, let's revisit the monster example. The presenter refactors the code to use composition, creating small, single-purpose functions that grant abilities.
Watch from 03:51 to 08:55. Observe how functions like swimmer and flier are created. These are then composed to build a flyingSwimmingMonsterCreator without any inheritance. This functional mixin approach is a powerful compositional pattern we'll build on in future lessons.
Now, let's see the composition-based solution for the image library.
Watch from 03:28 to 05:14. The refactoring here is key: Image becomes a simple data class, and file operations are moved into their own classes. Notice how a user can now flexibly combine these pieces: load a JPEG, draw on it, and save it.
By using composition, we gain:
- Flexibility: We can assemble objects with any combination of behaviors.
- Decoupling: Each component has a single responsibility and can be developed, tested, and reused independently.
- Better Encapsulation: Objects interact through well-defined public interfaces, not by reaching into each other's implementation details.
A Framework for Deciding: Guiding Principles
So, how do you decide when to use which? The phrase "favor composition over inheritance" suggests a default preference, but a deeper analysis is required. Given your background in computer science, you'll appreciate these more formal principles.
Prefer composition over inheritance?
This Stack Overflow thread is a fantastic collection of wisdom on the topic. We'll focus on a few key answers that provide the theoretical underpinnings for making an informed choice.
Please read through the answers highlighted below. They build on each other to form a comprehensive view: The 'Acid Test': Start with the top-voted answer by Gishu. Focus on the core idea: does TypeB need to expose the complete public interface of TypeA? This introduces the Liskov Substitution Principle (LSP). 'is a' vs. 'has a': Read the next highly-voted answer by Nick Zalutskiy. This is the classic, simple heuristic. Disadvantages of Inheritance: Scan the answer by Ahmed, which provides a concise bulleted list of the key disadvantages we've discussed (runtime inflexibility, broken encapsulation, tight coupling). Critique of 'is-a': Finally, read the detailed answer by Michael. It critiques the simple 'is-a' rule using the classic circle-ellipse or square-rectangle problem and introduces the 'fragile base class' concept. This is the most nuanced take.
Let's synthesize those readings into a decision-making framework.
1. The "IS-A" vs. "HAS-A" Heuristic
This is your first-level filter. Is the relationship fundamentally about identity or possession?
- A
Caris aVehicle. (Inheritance seems plausible). - A
Carhas anEngine. (Composition is appropriate).
2. The Liskov Substitution Principle (LSP)
This is the true "acid test" for inheritance. It states:
If
Sis a subtype ofT, then objects of typeTmay be replaced with objects of typeSwithout altering any of the desirable properties of that program.
In simpler terms: a subclass must be substitutable for its superclass everywhere, without causing surprises. The classic counter-example is the Rectangle and Square.
Object-oriented JavaScript: A Deep Dive into ES6 Classes
The Sitepoint article 'Object-oriented JavaScript' provides a perfect, code-based explanation of the Liskov Substitution Principle using the Rectangle/Square problem.
Please read the subsection 'IS-A and WORKS-LIKE-A'. Notice how even though a square is a rectangle mathematically, the Square class does not work like a Rectangle behaviorally, thus violating LSP and making inheritance a poor choice.
If a subclass needs to override a parent method in a way that fundamentally changes its contract (like the Square's setters), it violates LSP, and you should use composition instead.
Test your understanding!
Imagine you are designing a UI library. You have a base Component class that handles rendering to the DOM.
You need to create a Button that is clickable and a SelectDropdown that has a list of options and can be opened or closed.
Scenario: You also need an AutoCompleteInput, which is an input field that, when typed into, displays a dropdown of suggestions.
Should an AutoCompleteInput inherit from a SelectDropdown because it has a dropdown? Should it inherit from an InputField? Or is there a better way?
Describe your proposed design, choosing between inheritance and composition, and justify your choice based on the principles we've discussed (IS-A vs. HAS-A, LSP, flexibility).
Show answer
Inheritance is a poor choice here.
An AutoCompleteInput is not truly a SelectDropdown (it doesn't have a fixed list of options, its primary interaction is typing), nor is it just an InputField. Trying to force a single inheritance hierarchy would be messy and lead to the same combinatorial explosion we saw with the monsters (e.g., AutoCompleteWithIcons, AutoCompleteThatFetchesData). This also fails the "IS-A" test.
A much better design is composition:
An AutoCompleteInput has an InputField and it has a Dropdown.
Design:
- Create small, single-responsibility components:
InputField,Dropdown,Icon, etc. - The
AutoCompleteInputcomponent would be composed of anInputFieldinstance and aDropdowninstance. - It would coordinate the behavior between them: listening for
inputevents on theInputFieldand then populating and showing theDropdown.
Justification:
- Flexibility: This design is highly flexible. You could easily create an
AutoCompleteWithIconby composing it from anInputField, anIcon, and aDropdown. The components are reusable building blocks. - Decoupling: The
InputFielddoesn't need to know anything about theDropdown, and vice-versa. They are independent. TheAutoCompleteInputacts as a controller that wires them together. - Clarity (Single Responsibility): Each component does one thing well. An
InputFieldhandles text entry. ADropdownhandles displaying a list. This makes them easier to test and maintain.
Conclusion
Today we've confronted a central dilemma in object-oriented design. While inheritance is a powerful concept you've just mastered, it's a sharp tool that should be used with care. Understanding its trade-offs is a mark of an advanced developer.
Key Takeaways:
- Inheritance (
IS-A) creates tight coupling and rigid class hierarchies. It is best suited for stable, linear relationships where the subclass is a true behavioral subtype of the superclass. - Composition (
HAS-A) creates flexible and decoupled systems by assembling objects from smaller, independent, and reusable components. - When choosing, use the "IS-A" vs. "HAS-A" heuristic as a starting point, but always validate an inheritance choice against the Liskov Substitution Principle.
- The guiding principle "favor composition over inheritance" means you should start with composition as your default and only switch to inheritance when you have a strong justification for it.
Next Up
Now that we've established why composition is so often preferred, our next lesson will move from theory to practice. We will implement a simple mixin pattern by merging properties using Object.assign, taking our first concrete step toward building powerful objects through composition.