user3794478
user3794478

Reputation: 11

Issues with the Open/Closed Principle?

Was reading up on the Open/Closed principle of SOLID design and was curious about it's maintainability.

Lets say I have child class B and C which inherit from parent class A. B has methods unique to B, C has methods unique to C. Parent class A has two common methods that are utilized by the child classes.

In a future code release, let's say we have a new feature that introduces a common method between classes B and C. We now cannot push that method up to class A because it'd violate the "Closed for modification" portion of the principle. This seems to introduce code redundancy. Not only that, but technically wouldn't adding this new feature to classes B and C be also violate the modification tenet of the principle?

It seems with the Open/Closed approach you end up building an unnecessary, cascading hierarchy of child classes simply because one is not allowed to make alterations to the original code. Is this a correct assumption/understanding?

Upvotes: 1

Views: 634

Answers (2)

weston
weston

Reputation: 54781

You don't have a crystal ball, you can't see the future and predict that a change request will happen.

However once a change request has been made, it is much more likely another change in that area will come later.

Lets take your cars example from the comment: The moment that the change request for all cars to now honk is received you should be considering if another such change will come in later. Assuming you decide it's a good chance that it will, there's only one thing for it, that's to refactor to make this whole situation Open for extension and Closed for modification. So that it's not only easy to add honking now, but you can add the next such feature with ease.

You are correct that to do apply this prematurely can bloat code and it will also receive plenty of YAGNI comments during code reviews.

Upvotes: 1

Joe Ratzer
Joe Ratzer

Reputation: 18549

It seems with the Open/Closed approach you end up building an unnecessary, cascading hierarchy of child classes simply because one is not allowed to make alterations to the original code. Is this a correct assumption/understanding?

No I don't think following the open/closed principle results in cascading hierarchies of child classes.

Firstly, it's just a principle or goal. There might be times when adding a method to a base class is clearly the "right" approach even for SOLID devotees.

Secondly, a lot of methods in a base class (clearly resulting in changes) is a bit of a code smell to start with. Have you looked into the phrase "favour composition over inheritance"?

Upvotes: 0

Related Questions