SOLID – Like a (Open/Closed) Rock
TLDR: your code should be open for extension but closed for modification.
o Keep the current functions, Classes, modules immutable
o Extend, in a composable way (try to avoid inheritance as it tends to couple things)
Read the full article about the Open/Closed Principle from CodeBurst here
The main idea is that in one part of your code you have your abstractions such as classes that do one thing and do it well. You don't want to be modifying them and should be keeping them clean and cohesive.
You ready for this? The Open/Closed Principle = COMPOSITE DESIGN PATTERN – mind blown!
How about that, we’ve come full circle back to design patterns. Now… where’s that duck? Don’t get your beaks out of joint, no ducks this time we are going to be working with coffee machines instead. I really enjoy a great cup of coffee!
This article over on Stackify has a great code example of applying the Open/Closed Principle to a CoffeeMachine app.
To summarize: You have a BasicCoffeeMachine Class it has a constructor, a public method to add ground coffee, and a public method that brews a filter coffee. A BasicCoffeeApp class that prepares a HashMap with ground coffee, instantiates a BasicCoffeeMachine object, and calls the prepareCoffee method to brew the coffee. Pretty simple right? Our app brews us a fresh pot of filter coffee.
Well what if we upgrade our pot to include an integrated grinder? Now we can brew espresso also but our CoffeeApp doesn't support this kind of brewer. Sounds like some code changes to the CoffeApp are in order. Why don't we also update it so that we don't need to adapt to future types of coffee machines.
So how do we do this? Well, let's start off by extracting what we can to create an interface. Let's pull out what's mandatory for controlling a coffee machine, but none of the optional stuff. Since the only real "control" in the BasicCoffeeMachine is the brewCoffee method we can put that up in an interface and have BasicCoffeeMachine implement the interface (CoffeeMachine). Now we can add more implementations of CoffeeMachine.
See what we've done there? Just by adding the interface and implementing more variations of the CoffeeMachine we've adopted the Open/Closed Principle. So, what’s next? We’re not done refactoring, we need to modify the CoffeeApp to make use of the CoffeMachine interface by instantiating instances of it for the different coffee types.
Make mine a tall black with a shot of vanilla and please go check out the code example and the full article here.