SOLID Principles Demystified — (O)

Open/Closed Principle

Basura Ratnayake
2 min readApr 17, 2023

A class must be open for extension and be closed for modification, meaning an existing class must be extendable without having to be rewritten in order to implement new functionality.

Sample Scenario

Let’s use the same scenario with the AreaCalculator class and add new functionality to it. This time the user would like the sum of the area of additional shapes like triangles, semi-circle and etc.

Poorly Written

We would have to constantly modify this class by adding more conditional (If / Else) statements for each new shape we encounter.

This code is functionally correct but violates the Open/Closed Principle and make a mess of conditional statements.

Well Written

To remedy this violation, we must remove the logic to calculate the area of each shape out of the AreaCalculator class and attach it to each shape’s class as a new method called area.

And in order to bring consistency to the shape classes, we need to introduce an interface called IShape. With this approach you can add any number of shapes and pass it in when calculating the sum using the area method, without modifying the AreaCalculator class.

Major Benefits

  1. The AreaCalculator class need not be unit tested whenever a new resource type is added.
  2. Adding a new shape is fairly low risk as adding a new shape does not involve changes to the AreaCalculator class.
  3. Developer adding a new shape does not need tounderstand the inner workings of the AreaCalculator.

Next Liskov Substitution Principle

--

--

Basura Ratnayake

Full Stack Software Engineer | .NET, PHP, JavaScript, AWS Enthusiast | Passionate About Technology, Freedom, Sri Lanka, History, and Cryptocurrencies