What is the open/closed principle should be the firstquestion we ask. It states that an entity in a system should be open forextension and closed for modification. In terms of C# what it means to us is that a class should only bemodified if a bug is found on it. The rest of the time when we are doing newfunctionality we should create a new class.
For functionality that is related it implies that we inheritfrom the original object. In terms ofthis post the idea is to detect the conditions in which the code in question iseither breaking this principle or it will affect people trying to follow it onthe future. Which bring us to the followings which elements do we need to look at todetermine how will affect the people in the future?
When a project does not follow this principle duringexecution it ends up impacting the test surface and the amount of regressionneeded.
Let’s consider the following application:
It’s a web service it takes a small piece of xml with two valuesand operation that will be done to it brings back a result.
On the first iteration they created it with thefunctionality for adding since it was all that was needed.
It looked something similar to this:
Public class MathOperations()
Public long GetOperationResult(string xml)
This.Logger.StartOperationLog(parser.operand1, parser.operand2, parser.symbol);
Var parser = new OperationParser(xml);
If(parser.symbol == ”+”)
result = parser.operand1 + parser.operand2;
This.Logger.EndOperationLog(parser.operand1, parser.operand2, parser.symbol);
In the implementation above if you think about adding the other 3 operationsfor your second sprint would require to ensure that everything works once againsince changes in the main file might affect the processing of the addoperation. How can we make this classapply the principle and make it only impact the operation execution on our test?
One possible way to do it’s to write the original classusing a factory therefore adding next operations means that only a new classgets added into this project and only the new class needs to be tested.
It would look something similar to below.
result = OperationFactory.GetInstance(parser).DoOperation();
It means that after sprint one all the test you did for mathoperations wouldstill apply and not really need to be executed again.
On the next post I’m going to describe how to find out ifyour team actually adheres to this principles and what are things that can tellyou.