I understand that this principle states that a module is open for extension but closed for modification, and this is clear when we want to upgrade/modify a method in some class - we create another class that inherits the base class and then override the base method here in order to keep both functionalities.
But how about the case when we want to add another different method to the base class? Is this considered as modification or extension of the base class - is ok to add the method to the base class or we should also create new class that inherits the base class and then put new method there?
Also, same question for adding properties and fields to the base class.
TL;DR
I think adding a new method inherently means that you cannot violate OCP; as OCP mainly focuses on the reckless overriding of existing methods.
Example:
Base classCalculator
is inherited byMyCustomCalculator
. The base class only has methods for adding, subtracting, multiplying and dividing two numbers.
Creating a new method inMyCustomCalculator
, e.g.CalculateAverage(params int[])
does not violate OCP. It does not modify the logic behind any of the existing methods, it merely extends the methods that are provided by the calculator object.
New methods inherently do not change the old methods. Therefore, they don't modify existing logic; then simply extend what is available.
So no, it does not (inherently) violate OCP.
It's almost impossible for it to violate OCP, as creating something new is (inherently) completely different from modifying something that exists.
Some things to take note of though:
EDIT
I missed part of your question
is it ok to add the method to the base class or we should also create new class that inherits the base class and then put new method there?
That depends on context. For the Calculator
/ MyCustomCalculator
/ CalculateAverage()
example I provided; I would instinctively add it to the base class, as calculating averages is a basic operation that pertains to the responsibilities of a calculator.
However, if we were discussing adding a method that only pertains to complex numbers (MethodForComplexNumbers()
), then I would advocate the creation of a ComplexNumberCalculator
which inherits from Calculator
and implements MethodForComplexNumbers()
.
However, I think this is mainly due to SRP, not OCP.