Level Up Your Code: The SOLID Principles Quest | Open/Closed Principle

Kavindu Perera
2 min readApr 7, 2024

--

A bite-sized guide to understanding SOLID principles

  • Read the previous article via;
Photo by Glen Carrie on Unsplash

We now know that good code has well-defined parts, like Lego blocks (thanks to the Single Responsibility Principle).

Now, imagine being able to expand your Lego city without completely disassembling what you’ve already built. You could add a cool spaceship wing to your castle, or a rooftop garden to your house, all without starting from scratch.

The second SOLID principle, the Open/Closed Principle brings that amazing modularity to our code, letting us extend its functionality effortlessly. Let’s explore how to make our code just as adaptable!

The Perils of Rigid Code

Imagine a scenario where you’re building a simple application to calculate the area of different shapes. Here’s an example that violates the Open/Closed Principle:

Now, why is this problematic ???

  • Every time you want to support a new shape (like a triangle), you must modify the `calculateArea()` method, adding another `else if` block.
  • The more modifications you make within this method, the higher the risk of introducing bugs in the existing calculation logic.
  • Thoroughly testing this method requires running tests every single time you introduce a new shape.

Embracing Extensibility

Here’s how we can restructure the code to adhere to the Open/Closed Principle:

Why is this better ???

  • To add a new shape (e.g., Triangle), you simply create a `Triangle` class implementing the `Shape` interface — no need to alter the `AreaCalculator`. Open for extension.
  • The core logic of `AreaCalculator` remains untouched when new shapes are introduced. Closed for modification.
  • Each shape class can be tested in isolation.

What is the takeaway here ???

By using interfaces and abstractions, we make our code adaptable. We can introduce new features without disrupting existing ones, ensuring our codebase remains flexible and maintainable. Open for extension. Closed for modification.

And with that, we’ve taken another step towards code built to last! Stay tuned for the next SOLID exploration, where we’ll prepare our code to handle changes gracefully with the power of substitution!

--

--