Hacker News new | ask | show | jobs
by superdude264 4420 days ago
I'd love to see a pragmatic take on the open/closed principle. I've seen a colleague extend a class, override the method in question by copying in the code from the super-class, then modifying it in the sub-class. Afterward he then replaces all instantiations of the old class with the new class. 'Open for extension / closed for modification' seems like it would lead to a nightmare in a few years.
2 comments

So that is a really dogmatic approach to open/closed that is from the original formulation like 25 years ago. I've never encountered someone who would follow that practice when every instance needed to be changed (I assume Meyer would have construed that as a bug and allowed modification in that case). Even the less dogmatic Meyer definition of open/closed most people have left behind as it relies on implementation inheritance which is decidedly out of favor (and I believe rightly so).

In the more modern reading of the open/closed principle if you have multiple different variants on the behavior of a thing, you compose those variants in via an abstract interface. Then as you need to add even more variants you needn't change the original code any more only introduce more concrete implementations of the abstract interface that you compose at instantiation time as necessary. This approach is especially useful as your variant behavior grows. That is, a single boolean switch is probably easier to reason about than 2 implementations on an arbitrary interface. But once you get to 3 it becomes less obvious which is better. Any more than that and I usually reach for an interface without too much thinking about it.

Apply the Template Method pattern. The parent class doesn't seem to be extensible.