Today I Learned - Rocky Kev

TIL Open-Closed Principle in OOP

POSTED ON:

TAGS:

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:

TIL Why is TextEncoder a class

My assumed answer - it was for extension. What does reddit commenters have to say about it?

TIL Adapters, proxies, and decorators

An adapter provides a different interface to the object it adapts. A Proxy provides the same interface as its subject. A Decorator adds one or more responsibilities to an object.

TIL super()

When you use super(), it's like you're telling the new object to copy everything from the old object first, and then add or change anything else that's different.