Skip to content

Instantly share code, notes, and snippets.

@bhaveshdaswani93
Created January 4, 2020 08:54
Show Gist options
  • Save bhaveshdaswani93/1da104552eda0a4efd3c69fd14518863 to your computer and use it in GitHub Desktop.
Save bhaveshdaswani93/1da104552eda0a4efd3c69fd14518863 to your computer and use it in GitHub Desktop.
composition vs inheritance explained by example
// we have to represent human relation in oop style
class Human {
constructor(firstName,lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
sleepNow() {
console.log(`${this.firstName} ${this.lastName} is sleeping`)
}
eatNow() {
console.log(`${this.firstName} ${this.lastName} is eating`);
}
}
class Young extends Human {
constructor(firstName,lastName,age) {
super(firstName,lastName);
this.age = age;
}
startStudy() {
console.log(`${this.firstName} is studing`)
}
goToSchool() {
console.log(`${this.firstName} is going to school`)
}
}
class Male extends Young {
constructor(firstName,lastName,age,gender) {
super(firstName,lastName,age);
this.gender = gender;
}
// here all the method of young and human gets also Male does not need some of the method all method are made available to Male class
}
// The main issue with inheritance is that we predefine the whole architecture we have to define the whole chain of Human, Young,Male
// there properties and method this also make tight coupling suppose a method sleepNow has need some change like we want to perform
// prayer before sleep then it will effect the whole chain from where it being called this could be desired result but some time
// this could result in breakdown or unexpected behaviour
// How compose can solve this problem
getSleepAbility(human) {
return Object.assign({},human,{toSleep:()=>{console.log('this provide sleep ability.')}});
}
function man(firstName,lastName,age,gender) {
let man = {
firstName,
lastName,
age,
gender
};
return getSleepAbility(man);
}
// In FP programming we more focus on the what it has or what ability it has so i have created two function function man which get
// ability to sleep from getSleepAbility this way our code is future capable no tight coupling
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment