TIL Open-Closed Principle in OOP
POSTED ON:
In object-oriented programming, the open–closed principle (OCP) states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification";
To use an example:
// The base class
class Animal {
constructor(name, species) {
this.name = name;
this.species = species;
}
makeSound() {
throw new Error('Method not implemented');
}
}
If you want to wanted to make more methods, you can extend it.
But you cannot modify the base class!
// Everything else Extends off of the base class
class Dog extends Animal {
constructor(name) {
super(name, 'Dog');
}
makeSound() {
return 'Woof!';
}
}
class Cat extends Animal {
constructor(name) {
super(name, 'Cat');
}
makeSound() {
return 'Meow!';
}
}
class Cow extends Animal {
constructor(name) {
super(name, 'Cow');
}
makeSound() {
return 'Moo!';
}
}
Sweet! Now to see it in action:
// Test
function makeAnimalSound(animal) {
console.log(`${animal.name} the ${animal.species} says ${animal.makeSound()}`);
}
// Run your code
const cow = new Cow('Betsy');
makeAnimalSound(cow); // Betsy the Cow says Moo!
Related TILs
Tagged: oop