Open/Closed Principle
Learn how to add new behaviour by writing new classes instead of editing code that already works, using a discount example, and how to avoid building for changes that never come.
Think about the electric sockets in your home. When you buy a new gadget, such as a lamp, a phone charger or a fan, you just plug it in. Nobody opens the wall, cuts the wires and rebuilds the socket for each new device. The socket is closed for modification (nobody changes it) but open for extension (you can plug in any new device that fits the standard shape).
Good software can work the same way. This is the second SOLID principle, and it says:
Software parts (classes, modules, functions) should be open for extension but closed for modification.
In plain words: when a new requirement arrives, you should be able to add new code, without editing the old code that already works.
01Why editing working code is risky
Every time you open a class that is already working and tested, you take a risk. You might break something that was fine. You must run all the tests again. And if several developers edit the same class at the same time, they cause conflicts.
So we would like a design where the common change (a new kind of something) is done by adding a class, and the old classes stay exactly as they are.
Loading the rest of the lesson…