conectionist
conectionist

Reputation: 2924

Does overriding violate the Open/Closed principle?

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?

Upvotes: 9

Views: 2350

Answers (4)

zzfima
zzfima

Reputation: 1565

Form "Adaptive Code via C#" book, virtual methods is a instrument to achieve OCP.

Upvotes: 0

plalx
plalx

Reputation: 43718

"I thought that the modification part referred strictly to altering the source code of the base class."

You thought right.

There is a plethora of ways to make a class extensible and allowing one to inherit from it is one of them. The keyword extend is even used in a few languages to enable inheritance which makes it quite obvious that we aren't modifying, we are extending...

Whether inheritance is the right solution to extensibility or not is another concern, but usually it is not though. Composition should be the preferred way to make classes extensible (e.g. Strategy, Observer, Decorator, Pipes and Filters, etc...)

Upvotes: 3

Steven
Steven

Reputation: 172646

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

Upvotes: 5

usr
usr

Reputation: 171178

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.

Upvotes: 2

Related Questions