What does “favor object composition over class inheritance” mean?

Experience Level: Medior
Tags: JavaScript

Answer

Favor object composition over class inheritance is a principle in object-oriented programming that suggests that it is often better to use object composition instead of class inheritance to achieve code reuse and extensibility.

Inheritance is a mechanism in which a class can inherit properties and methods from a parent class, but this can lead to a rigid and inflexible class hierarchy. In contrast, object composition involves creating objects that contain other objects, which can be used to build up more complex objects and behaviors.

By favoring object composition over class inheritance, developers can create more flexible and reusable code that is easier to maintain and extend over time. Object composition also allows for greater code reuse, since objects can be easily reused and combined to create new objects and behaviors.

Here's an example of object composition in JavaScript:

const person = {
  firstName: 'John',
  lastName: 'Doe',
  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

const employee = {
  jobTitle: 'Developer',
  salary: 100000,
  getJobInfo() {
    return `${this.jobTitle} - ${this.salary}`;
  }
};

const johnDoe = Object.assign({}, person, employee);

console.log(johnDoe.getFullName()); // Output: John Doe
console.log(johnDoe.getJobInfo()); // Output: Developer - 100000

In this example, we create two objects (person and employee) that represent different aspects of a person's identity. We then use the Object.assign() method to create a new object (johnDoe) that combines the properties and methods of both objects. By using object composition, we can create new objects that have the properties and methods of multiple objects, without having to rely on class inheritance.

Comments

No Comments Yet.
Be the first to tell us what you think.