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 class Calculator
is inherited by MyCustomCalculator
. The base class only has methods for adding, subtracting, multiplying and dividing two numbers.
Creating a new method in MyCustomCalculator
, 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:
- I can think of one (arguable) exception to this: overloading. If you create a new method that overloads an existing one, then you are responsible to abide by the rules of overloading. Most notably, this means that overloaded methods should perform the exact same task as eachother (overloaded methods are simply based on different input parameters, but their processing and output should be functionally equivalent). Although I am not 100% sure if this is a violation of OCP (because it wrongly extends a base class), or SRP (because it creates an ambiguous responsibility as to the processing/output of the overloaded methods). It seems like a bit of both.
- The same principle applies even if your new method does not overload an existing one. Is the new method relevant enough to the responsibility (intention/purpose) of the base class? Because if it is very different, then you might be violating SRP.
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.