18

I understand the intent of the open-closed principle. It's meant to reduce the risk of breaking something that already works while modifying it, by telling you to try to extend without modifying.

However, I had some trouble understanding how this principle is applied in practice. To my understanding, there are two ways to apply it. Beofore and after a possible change:

  1. Before: program to abstractions and 'predict the future' as much as you can. For example, a method drive(Car car) will have to change if Motorcycles are added to the system in the future, so it probably violates OCP. But the method drive(MotorVehicle vehicle) is less likely to have to change in the future, so it adheres to OCP.

    However, it's quite difficult to predict the future and know in advance what changes are going to be made to the system.

  2. After: when a change is needed, extend a class instead of modifying it's current code.

Practice #1 isn't hard to understand. However it's practice #2 that I'm having trouble understanding how to apply.

For example (I took it from a video on YouTube): let's say we have a method in a class that accepts CreditCard objects: makePayment(CraditCard card). One day Vouchers are added to the system. This method doesn't support them so it has to be modified.

When implementing the method in the first place we failed to predict the future and program in more abstract terms (e.g. makePayment(Payment pay), so now we have to change the existing code.

Practice #2 says we should add the functionality by extending instead of modifying. What does that mean? Should I subclass the existing class instead of simply changing it's existing code? Should I make some kind of wrapper around it just to avoid rewriting code?

Or does the principle not even refer to 'how to correctly modify/add functionality', but rather refers to 'how to avoid having to make changes in the first place (i.e. program to abstractions)?

2
  • 1
    Open/Closed Principle doesn't dictate the mechanism you use. Inheritance is usually the wrong choice. Also, it's impossible to guard against all future changes. It's best not to try to predict the future, but once a change is needed, modify the design so future changes of that same kind can be accommodated.
    – Doval
    May 12, 2014 at 16:45

3 Answers 3

16

Design principles always have to be balanced against each other. You can't predict the future, and most programmers do it horribly when they try. That's why we have the rule of three, which is primarily about duplication, but applies to refactoring for any other design principles as well.

When you only have one implementation of an interface, you don't need to care much about OCP, unless it's crystal clear where any extensions would take place. In fact, you often lose clarity when trying to over-design in this situation. When you extend it once, you refactor to make it OCP friendly if that's the easiest and clearest way to do it. When you extend it to a third implementation, you make sure to refactor it taking OCP into account, even if it requires a little more effort.

In practice, when you only have two implementations, refactoring when you add a third is usually not too difficult. It's when you let it grow past that point that it becomes troublesome to maintain.

2
  • 2
    Thanks for answering. Let me see if I understand what you're saying: what you're saying is that I should care about OCP mainly after I was forced to make changes to a class. Meaning: when implementing a class for the first time, I shouldn't worry much about OCP, since it's hard to predict the future anyway. When I need to extend/modify it for the first time, maybe it's a good idea to refactor a little to be more flexible in the future (more OCP). And in the third time I need to extend/modify the class, it's time to do some refactoring to make it more adhering to OCP. Is this what you mean?
    – Aviv Cohn
    May 21, 2014 at 12:54
  • 1
    That's the idea. May 21, 2014 at 13:14
3

I understand the intent of the open-closed principle. It's meant to reduce the risk of breaking something that already works while modifying it, by telling you to try to extend without modifying.

It is also about not breaking all the objects that rely on that method by not changing the behavior of already existing objects. Once an object has advertised behavior changing it is risky as you are altering the known and expected behavior of the object without knowing exactly what other objects expect that behavior.

What does that mean? Should I subclass the existing class instead of simply changing it's existing code?

Yup.

"Only accepts credit cards" is defined as part of the behavior of that class, via its public interface. The programmer has declared to the world that this object's method only takes credit cards. She did it using a kinda not particularly clear method name, but its done. The rest of the system is relying on this.

That might have made sense at the time, but now if it needs to change now you should make a new class that accepts things other than credit cards.

New behavior = new class

As an aside - A good way of predicting the future is to think about the name you have given a method. Have you given a really general sounding method name like makePayment to a method with specific rules in the method as to exactly what payment it can make? That is a code smell. If you have specific rules these should be made clear from the method name - makePayment should be makeCreditCardPayment. Do this when you are writing the object the first time and other programmers will thank you for it.

3
  • This is old but hopefully I can get a reply, so with OCP is it more about "behaviour" as with LSP? The thing I never understood (and reason why I am back reading about OCP) is how you can never change a methods body as I am pretty sure on every project I have worked on and all code reviews I have been a part of changing code within some method(s) is pretty standard.
    – berimbolo
    Nov 10, 2021 at 8:58
  • 1
    Changing the existing method is common because it is quick and easy and most people don't understand why you wouldn't. The reason you wouldn't is that this method already works and is relied upon by the system. So it is a risk that you will break the system or introduce bugs. So don't touch it. In OOP you don't need to touch it because you can leverage polymorphism. You can put the new behaviour in a new class with same interface and have the code call that instead. Old class remains untouched since the code isn't bound to the exact object it is calling Nov 11, 2021 at 9:10
  • 2
    Something you find when you follow SOLID principles is that you write a lot of small focused classes with nice tests and then you never go back to them, despite your code base constantly changing. The change is introduced by new classes that operate slightly different to what came before. So you are no longer constantly re-writing your code as your system evolves (which risks introducing bugs or breaking dependencies) and instead it is new classes being written and existing code remaining the same. Nov 11, 2021 at 9:14
2

I think you are looking too far into the future. Solve the current problem in a flexible way which adheres to open/closed.

Let's say you need to implement a drive(Car car) method. Depending on your language you have a couple of options.

  • For languages which support overloading (C++), then just use drive(const Car& car)

    At some point later you might need drive(const Motorcycle& motorcycle), but it won't interfere with drive(const Car& car). No problem!

  • For languages which don't support overloading (Objective C), then include the type name in the method -driveCar:(Car *)car.

    At some point later you might need -driveMotorcycle:(Motorcycle *)motorcycle, but again, it won't interfere.

This allows drive(Car car) to be closed to modification, but is open to extending to other vehicle types. This minimalist future planning which allows you to get work done today, but keeps you from blocking yourself in the future.

Trying to imagine the most basic types you need can lead to infinite regress. What happens when you want to drive a Segue, a bicycle or a Jumbo jet. How do you construct a single generic abstract type which can account for all devices people get into and use for mobility?

5
  • Modifying a class to add your new method violates the Open-Closed Principle. Your suggestion also eliminates the ability to apply the Liskov-Substitution Principle to all vehicles that can drive which essentially eliminates one of the strongest parts of OO.
    – Dunk
    May 21, 2014 at 13:38
  • @Dunk I based my answer on the polymorphic open/closed principle, not the strict Meyer open/closed principle. It's allowable to update classes to support new interfaces. In this example, the car interface is kept separate from the motorcycle interface. These could be formalized as separate driving abstract classes for car and motorcycle which the implementing class could support. May 21, 2014 at 14:15
  • @Dunk The Liskov-Substitution Principle is useful, but does not come for free. If the original specification only requires a car, then creating a more generic vehicle may not be worth the extra cost of money, time, and complexity. In addition, it is unlikely that a more generic vehicle will be perfectly suited to handle unplanned subclasses. Either the interface for a motorcycle will need to be shoehorned into the vehicle interface (which was designed to only handle car), or you will need to modify vehicle to handle motorcycle (a real violation of open/closed). May 21, 2014 at 14:27
  • Liskov-Substitution principle doesn't come for free but it also doesn't come with much cost either. And usually it pays back far more than it ever costs many times over even if another subclass is never inherited from it in the main application. Applying LSP makes automated testing far easier, which is a win already. Also, while you certainly shouldn't go hog wild and assume everything is going to need LSP, if you are building an application and don't have a good feel for what is likely to need it in a future rev then you don't know enough about your application or its domain.
    – Dunk
    May 21, 2014 at 18:34
  • 2
    With regards to definition of OCP. It might be the industries that I have worked in, which tend to require higher levels of verification than just an ordinary commercial company, but generally speaking if a file/class changes then not only do you need to retest the file/class but everything that makes use of that file/class in your regression testing. So it doesn't matter if someone says polymorphic open/closed is fine, changing the interface has wide ranging consequences so it isn't all that fine.
    – Dunk
    May 21, 2014 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.