SOLID Pattern — Mastering the Open-Closed Principle

Kevin Bartsch
2 min readMar 11, 2024

--

Today, let’s go through the world of software craftsmanship, spotlighting the useful Open-Closed Principle (OCP) with TypeScript.
Level: Intermediate

The Open-Closed Principle, as phrased by Bertrand Meyer, advises us to “be open for extension but closed for modification.” So in another way where you add a new function to your application, you should not disturbe any other functionality of it.

Let’s have a look to a TypeScript zoo management system example. (Note: This principle is like all SOLID patterns not restricted to a coding language and can be used differently. For example in angular as a component handling or service structure) We’ve got a base class for animals, and we aim to add new feeding functionalities without disrupting the existing choreography. Behold, the OCP:

abstract class Animal {
abstract makeSound(): string;
}
class Lion extends Animal {
makeSound(): string {
return "Roar!";
}
}
class Elephant extends Animal {
makeSound(): string {
return "Trumpet!";
}
}
// OCP-compliant extension
class ZooKeeper {
feed(animal: Animal): void {
console.log(`Feeding ${animal.constructor.name}: ${animal.makeSound()}`);
}
}
// Usage
const lion = new Lion();
const elephant = new Elephant();
const zooKeeper = new ZooKeeper();
zooKeeper.feed(lion);
zooKeeper.feed(elephant);

In this TypeScript example, we extend our zoo system’s functionality without tweaking the existing Animal class. Exactly what we wanted to achieve! Nice!

💡Pros:

  1. Type-Safe Expansion: TypeScript enforces types, making the extension process more secure and your refactorings less prone to unexpected surprises.
  2. Maintainable: The existing code remains untouched, ensuring the performance remains en pointe during the regular process.

🚨Cons:

  1. Abstraction: Crafting abstract classes and interfaces may seem akin to constructing an intricate blueprint. However, much like an architect’s design brings sophistication to a structure, abstraction imparts elegance to the art of coding.
  2. Over-Engineering: Navigating the delicate balance between elegance and overkill is akin to performing a nuanced duet. Resist the temptation to transform a graceful step into an extravagant leap, maintaining the harmony in your code composition.

In conclusion, TypeScript empowers us to effortlessly explore the coding terrain, where new features seamlessly integrate with the existing landscape. To my fellow TypeScript enthusiasts, foster extensibility in your classes while maintaining a vigilant guard against unnecessary modifications. Hope this brief lecture was helpful. Until our next coding session, happy Coding!

Photo by Brooke Cagle on Unsplash

--

--

Kevin Bartsch

Passionate Developer, UX/UI Aficionado. Sharing knowledge, igniting connections. Let's build, learn, and create something extraordinary! ✨