Encapsulation
Inheritance
Implementation Inheritance
: Means that data and methods defined on a parent class are available on objects created from classes that inherit from those parent classes.Prototypal Inheritance
: Means that JS uses prototype objects to make its implementation inheritance
actually work.class Charity {}
class Business {
toString() {
return "Give us your money.";
}
}
class Restaurant extends Business {
toString() {
return "Eat at Joe's!";
}
}
class AutoRepairShop extends Business {}
class Retail extends Business {
toString() {
return "Buy some stuff!";
}
}
class ClothingStore extends Retail {}
class PhoneStore extends Retail {
toString() {
return "Upgrade your perfectly good phone, now!";
}
}
console.log(new PhoneStore().toString()); // 'Upgrade your perfectly good phone, now!'
console.log(new ClothingStore().toString()); // 'Buy some stuff!';
console.log(new Restaurant().toString()); // 'Eat at Joe\'s!'
console.log(new AutoRepairShop().toString()); // 'Give us your money.'
console.log(new Charity().toString()); // [object object]
The nuts and bolts of prototypal inheritance
class Parent {
constructor() {
this.name = "PARENT";
}
toString() {
return `My name is ${this.name}`;
}
}
class Child extends Parent {
constructor() {
super();
this.name = "CHILD";
}
}
const parent = new Parent();
console.log(parent.toString()); // my name is Parent
const child = new Child();
console.log(child.toString()); // my name is Child
Polymorphism
SOLID is an anagram for:
The Single-Responsibility Principle
The Open-Close Principle
The Liskov Substitution Principle
The Interface Segregation Principle
The Dependency Inversion Principle
Single-Responsibility Principle
A class should do one thing and do it well
The Liskov Substitution Principle
Subtype Requirement: Let ϕ(x) be a property provable about objects x of type T. Then ϕ(y) should be true for objects y of type S where S is a subtype of T.
You can substitute child class objects for parent class objects and not cause errors.
The Other Three
The remaining three principles are important for languages that have static typing
- which means a variable can have only one kind of thing in it.
Open-Close Principle
A class is open for extension and closed for modification.
Interface Segregation Principle
Method names should be grouped together into granular collections called “interfaces”.
Dependency Inversion Principle
Functionality that your class depends on should be provided as parameters to methods rather than using new in the class to create a new instance.
Coupling
: The degree of interdependence between two or more classes.Here is the formal definition:
A method of an object can only invoke the methods (or use the properties) of the following kind of objects:
You cannot cheat by seperating extra calls onto different lines.
When to ignore the Law of Demeter