Composition vs Inheritance

Inheritance is a parent class that is extended to smaller pieces that add or overwrite things.

Function composition is an operation that takes two functions a and b and produces a function h such that h(x) = a(b(x)). Which means we can use at least two abilities.

Here is an inheritance example.

class Person {
    constructor(name, country, language) {
        this.name = name;
        this.country = country;
        this.language = language;
    }
    speak() {
        return this.name + " can speak " + this.language;
    }
}

class American extends Person{
    constructor (name, country, language, location){
        super(name, country, language);
        this.location = location;
    }
    think(){
        return "Think by " + this.language;
    }

}

const tim = new American("Tim", "USA", "English", "North");

console.log(tim.speak());
console.log(tim.think());
console.log(tim.name);
console.log(tim.country);
console.log(tim.language);
console.log(tim.location);
Tim can speak English
Think by English
Tim
USA
English
North

For example, the American class is extended the functionality and value from the People class.

However, Composition is smaller pieces to create something bigger.

Here is a composition function example.

const compose = (a, b) => (data) => a(b(data));
const multiplyBy5 = (num) => num * 5;
const makePositive = (num) => Math.abs(num);

const multiplyBy5andMakePositive = compose(multiplyBy5, makePositive);
console.log(multiplyBy5andMakePositive(-50));
250

The debate between composition vs inheritance is a pretty heavy one and a lot of people prefer composition over inheritance.

Inheritance are structure and the structure of our code is around what it is. that is what is the American class and what is the People class. We are structuring our classes around what things are they have data as well as methods.

On the other hand, Composition, we focus what is the ability of function and what it does to data.

  • Inheritance is focusing on what it is.
  • Composition is focusing on what is the abilities.

Leave a Reply

Your email address will not be published.

ANOTE.DEV