The open/closed principle states that a class should be open for extension but closed for modification.
I thought that the modification part referred strictly to altering the source code of the base class. But I had an argument with someone saying that this also involves overriding methods from the base class.
It this interpretation correct?
This has several disadvantages: The resource allocator code needs to be unit tested whenever a new resource type is added. Adding a new resource type introduces considerable risk in the design as almost all aspects of resource allocation have to be modified.
In a nutshell, the developer must need to change only a specific part of the code (a class or a function) every time a requirement changes. Using a statically typed language like Java, C#, etc. the open/closed principle is generally achieved by using inheritance and polymorphism.
In object-oriented programming, the open–closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"; that is, such an entity can allow its behaviour to be extended without modifying its source code.
For example, the Decorator pattern offers us to follow the Open Close principle. Furthermore, we may use the Factory Method, Strategy pattern and the Observer pattern to design an application with minimum changes in the existing code. That's all about 'SOLID Principles : The Open Closed Principle'.
Virtual methods allow replacing behavior of a base class in a derived class, without having to alter the base class and this means you adhere to the Open/Closed principle since you can extend the system without having to modify existing code.
Base classes (that are not purely abstract) however, tend to violate the Dependency Inversion Principle, since the derived class takes a dependency on the base class, which is a concrete component instead of being an abstraction. Remember, the DIP states that:
High-level modules should [...] depend on abstractions.
Besides this, base classes tend to violate the Interface Segregation Principle as well in case they define multiple public (or protected) methods that are not all used by the derived type. This is a violation of the ISP because:
no client should be forced to depend on methods it does not use
An override is a lot like a callback that anyone can register. It's like:
if (IsOverridden) CallCallback();
else DefaultImplementation(); //possibly empty
In that sense there is no modification. You are just reconfiguring the object to call the callback instead of doing the default behavior.
It's just like the click event of a button. You wouldn't consider subscribing to an event a modification. It's extension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With