This is part 2 in a series of posts about the SOLID design principles. Check out part 1 here
Open Closed Principle
One of the only guarantees in software development is that requirements are going to change. It may be during initial development, in 6 months, or even 6 years. Most likely it will be all three (and a lot more in between). Modularizing your code is a great way to minimize the impact of these changes. Writing code that conforms to the Open Closed Principle is one way to help you accomplish this goal.
Here is an example:
Letâ€™s pretend your uncle just gave you a stock â€˜95 Ford Mustang. After driving it around for a few weeks you decide it needs some more horsepower.
You have two options:
You can cut the engine block in half and splice weld in half another engine you found in the junkyard. This will increase you cylinder count from 6 to 10, which should definitely give you more power. You will also need to make similar modifications to the exhaust manifold and crankshaft.
Total Cost: $17,843.28
Total Hours Spent: 321
Total Added Horsepower: 16
You can purchase a turbocharger specifically designed for your car and bolt it on to your engine.
Total Cost: $1,723.47
Total Hours Spent: 1 afternoon
Total Added Horsepower: 350
Which option would you choose?
Cars are designed in a modular way that makes it easy to swap out and add new parts. Software should be designed the same way.
The Open Closed Principle describes modules that have two main characteristics: (1) open for extension, and (2) closed for modification. The basic idea here is that we should aim to write code that does not have to be changed every time the requirements change (see above).
So how do you actually do this? The answer is through abstraction.
Here's an example:
In the first version of the Car class above we have one general class that handles the properties and behaviors for several types of cars. The problem with this is that every time we want to add a new type of car or a new feature we have to modify the Car class. The way around this is to make the Car class abstract. This allows us to just extend the Car class with new implementation details whenever we want to create a new type of car.
Crafting your code in this way will help you to minimize refactoring and embrace change. I hope this simple example of the Open closed Principle was helpful to you. To read more about it check out Bob Martin's book: Agile Principles, Patterns, and Practices in C#.