[C#] Open-Closed principle pattern in SOLID principle patterns
Posted in : Technologies on by : zquanghoangz Comments: 4 Tags: C#, DesignPatterns, SOLID
In order to study SOLID principle, the one I’m interested in is Open-Closed principle that wants to represent on this topic.
Firstly, let see the definition on Wiki: In object-oriented programming, the open/closed principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification“;
In the first place when I read that definition, I quickly miss understanding with Extension methods of C#, included the sealed keyword. It means not to modify class itself then we can extend by using extension methods.
But the true is something more than that. So let take a look at some pieces of code.
You can see that depend on the operator, we will calculate a result in a different way. That code for sure running as expected. I can guarantee it in below test case.
So, what problem here? You also see it has some operators, then it might have more operator in the future (eg: the division “/”). With the new operation, we should modify the function and class, it’s not “closed for modification”, more than that it might have risks in some case.
What I will do is try to exclude the business of calculation result for each operator itself to other class using a provider and single calculator, those interfaces look like:
And the calculator class will change a bit:
The idea is IOperatorsProvider will store all operators and provide the matched ISingleCalculator with input string operator. Each ISingleCalculator will be responsible for calculation business itself.
Now, it’s time to implement a single calculator:
The code is not much changing the business, we separate check operator and calculative result in 2 methods.
Then we implement IOperatorsProvider here:
Note that every time we add a new operator, we should change the code in Constructor method. You might question, oh “you just create a new method that not closed for modification”, sh*t that’s crazy, but not really, what we focus on implementing principle is Calculator class, that you will see I commented //Something else in above code, “something else” is the reason that we don’t want to take risk to modify class ever again, but OperatorsProvider class is not.
So now, we change a bit to make the test run:
Ok, everything seems finished.
You might ask a question, why should I change a simple code with a bundle of complex / head-each code?
Yes, it’s absolutely not valuable in this example, but in the real project, we might have very complicated business in each SimpleCalculator, apply Open-Closed principle will make you easy understand and maintenance.
Hope you enjoy it.