4 ms·
Essentially, it means that you can extend something by writing _new_ code, in a _new_ file, rather than modifying some code. For example, a case statement cann
by charlieflowers 7y ago
Essentially, it means that you can extend something by writing _new_ code, in a _new_ file, rather than modifying some code.
For example, a case statement cannot be modified without adding a new case. But something that finds all objects which implement IFoo and uses them can be modified by implementing a new implementer of IFoo. (That's not the only and probably not the best example, but it is an example).
A lot of people don't realize that most (maybe all) of these principles originated on C++ code bases way back, where changing one file in one tiny way could cause massive number of files to need recompiling -- which at the time was very painful due to slow compilers.
They have some good applicability, but I think they're massively over-sold.
- zmmmmm 7y agoThanks. That makes "open for extension" clear, but it still leaves me wondering about "closed for modification". It is certainly a nice aspiration that code doesn't need to be modified to customize it if one can achieve that. But failing that, code should be as modifiable as we can possibly make it. Making it "closed for modification" sounds like a bad thing, like it will be very hard to maintain.
- mdpopescu 7y agoChanging an existing class (modification) is possibly bad, because it can introduce bugs. The code was working, you made a change, oops! Adding a new class (when the code was written to be extensible) should prevent that. See for example [1] where Sandi Metz shows how to rewrite some incredibly complex code to make that possible. [1] https://www.youtube.com/watch?v=8bZh5LMaSmE https://www.youtube.com/watch?v=8bZh5LMaSmE
- dsego 7y agoThis is my interpretation. Usually bad devs I've worked with will mistakenly keep things DRY by reusing code in a bad way, for example modifying existing classes to handle cases they were not meant to handle. The most primitive example is reusing a function because it does 80% of some logic and then adding some bool flags to make it do something a bit different. Instead one should always abstract things and extract reusable bits, but only if it makes sense. But more often than not, lazy or misguided devs will see a similar piece of code and try to reuse it by modifying it to add new behavior, because "copy/pasting is bad".