3. Open/Closed Principle (OCP) Flashcards
What does the OCP state?
That software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.
What does the OCP mean in relation to methods?
It should be possible to change the behaviour of a method without editing its source code.
What does “open to extension” mean?
That new behaviour can be added in the future.
What does it mean if a module in our code is “closed to extension”?
That the module has a fixed behaviour.
What does “closed to modification” mean?
That it’s unnecessary to change the source or binary code of the system.
What can be said about the closedness to modification of a class that is closed to extension?
The only way to change the behaviour of code that is closed to extension is to change the code itself. So, by definition, it is not closed to modification.
Why should code be closed to modification?
- The less we need to change the source of our code, the less likely it is that we’ll introduce new bugs to it.
- Less likely to break dependent code because we don’t have to deploy updates on the given module.
- Fewer conditionals in code that is open to extension results in simpler code.
- Bug fixes are OK.
What are the considerations around using abstractions in code?
- Balance abstraction with concreteness.
- Abstraction adds complexity.
- Predict where variation is needed and apply abstraction as needed.
How do you decide where to make your application extensible while balancing extreme concreteness and extreme abstraction?
- Start concrete
- When changes are needed, modify the code the first time or two
- By the third modification or so, consider making the code open to extension for that axis of change
What are the three approaches to implementing OCP?
- Parameters
- Inheritance
- Composition/Injection
Should you use new classes for new features, and why?
Yes!
- Have the chance to design the class to perfectly suit the problem at hand. No need to work around existing code or bad patterns that might be there.
- Nothing in the current system will depend on the newly created class because until now it didn’t exist!
- Can add behaviour without touching existing code.
- The newly created class can immediately follow SRP if the class that’s using it has a lot of responsibilities.
- Can be unit tested since you’re designing from scratch.
How does OCP relate to NuGet packages?
OCP is especially important in NuGet packages. Whether public or internal, NuGet packages are closed for modification by their consumers and new versions of the package must not break the existing code.
What are the key takeaways of this module?
- Solve the problem first using simple, concrete code
- Identify the kinds of changes the application is likely to continue needing
- Modify code to be extensible along the axis of change you’ve identified