Course contentsShow
← JavaScript
Lesson 1823 of 2,72338. Object-Oriented PatternsFree lesson

Composition with Classes

Combine composition and classes by having class instances delegate to composed helper objects instead of extending.

Composition with Classes

You'll learn how to use composition within a class-based architecture by delegating behavior to helper objects instead of relying on inheritance.

The Core Idea

You've seen composition with factories and mixins. But what if your codebase uses classes? You can still favor composition over inheritance by having your class delegate specific responsibilities to composed helper objects. Instead of extending a parent class for every new capability, you inject small, focused objects that handle specific tasks.

How It Works

Rather than cramming all behavior into a class hierarchy, you:

  1. Create small helper objects or classes that handle one thing well
  2. Pass them into your main class via the constructor
  3. Call methods on those helpers when needed

Think of it like a manager delegating tasks to specialists instead of trying to do everything themselves.

class Logger {
  log(message) {
    console.log(`[LOG]: ${message}`);
  }
}

class Validator {
  isValid(data) {
    return data && data.trim().length > 0;
  }
}

class User {
  constructor(name, logger, validator) {
    this.name = name;
    this.logger = logger;
    this.validator = validator;
  }

  save() {
    if (this.validator.isValid(this.name)) {
      this.logger.log(`Saving user: ${this.name}`);
      // Save logic...
    } else {
      this.logger.log('Invalid user data');
    }
  }
}

const user = new User('Alice', new Logger(), new Validator());
user.save(); // [LOG]: Saving user: Alice

The User class doesn't inherit logging or validation—it composes them. This keeps User focused and makes testing easier (you can inject mock helpers).

Key Takeaway: Composition with classes means injecting helper objects into your class instances, delegating specific tasks to them instead of building deep inheritance hierarchies.