Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

As I have had it explained, the open/close principle states that once written code should not be modified (aside from bug fixes). But if my business rules change shouldn't I modify the code implementing those changes? I suspect I'm not understanding something about how the principle because it doesn't make sense to me.

share|improve this question

4 Answers 4

This is probably the hardest of the solid principles to explain. Let me try. Imagine you wrote an Invoice class that works perfectly and has no bugs. It makes a PDF of an invoice.

Then someone says they want an HTML invoice with links in it. You don't change any code in Invoice to satisfy this request. Instead, you make another class, HTMLInvoice, that does what they now want. You leverage inheritance so that you don't have to write a lot of duplicate code in HTMLInvoice.

Old code that was using the old Invoice isn't broken or really affected in any way. The new code can use HTMLInvoice. (If you also do Liskov Substitutability, the L of solid, you can give HTMLInvoice instances to existing code that's expecting Invoice instances.) Everyone lives happily ever after.

Invoice is closed to modification, open to extension. And you have to write Invoice properly in advance for this to work, btw.

share|improve this answer
1  
If the business rules change there is no assumption of working perfectly with no bugs, so the open/close principle doesn't apply? –  JeffO Nov 17 '10 at 20:06
    
I struggled with this rule myself and what Kate suggests is basically what I've concluded on it. In business, you try to program smaller, more flexible classes so you can reuse them well. If you got them working right, you don't want to modify them. But they rarely are fully "done" so some modifying is inevitable. Note that the text says "module" though, not object. I often successfully apply the OCP at the function level, with tight functions that do one thing perfectly and never need changing. –  CodexArcanum Nov 17 '10 at 21:36
1  
@Jeff O I distinguish between fixing a bug (where the code didn't meet the original requirement and nobody wants it as it is) and changing the requirements. If I require PDFs and the code makes PDFs, there's no bug, even though I now want HTML (and usually people want HTML as well, not instead of.) –  Kate Gregory Nov 17 '10 at 23:53
2  
@Winston - this is what I meant when I said you have to write Invoice properly. Ideally there was already a pretty abstract invoice and you inherited PDFInvoice expecting this. If not, you have to break the rule once to set yourself up to not break it in the future. Either way, predicting future changes is a huge part of all this - and that's the "catch and cut up an elephant" part of the recipe. –  Kate Gregory Nov 18 '10 at 1:35
1  
Your last statement is the most important. Open/closed is a design ideal--and you have to get the design right up front to achieve it. Not everything needs to satisfy open/closed, either, but it's a powerful tool if you can get there. –  Alex Feinman Sep 12 '13 at 14:43

Have you read the The Open-Closed Principle article by Uncle Bob's pals at ObjectMentor? I think it's one of the better explanations out there.

There are many heuristics associated with object oriented design. For example, “all member variables should be private”, or “global variables should be avoided”, or “using run time type identification (RTTI) is dangerous”. What is the source of these heuristics? What makes them true? Are they always true? This column investigates the design principle that underlies these heuristics -- the open-closed principle.

As Ivar Jacobson said: “All systems change during their life cycles. This must be borne in mind when developing systems expected to last longer than the first version.” How can we create designs that are stable in the face of change and that will last longer than the first version? Bertrand Meyer gave us guidance as long ago as 1988 when he coined the now famous open-closed principle. To paraphrase him:

SOFTWARE ENTITIES (CLASSES, MODULES, FUNCTIONS, ETC.) SHOULD BE OPEN FOR EXTENSION, BUT CLOSED FOR MODIFICATION.

When a single change to a program results in a cascade of changes to dependent modules, that program exhibits the undesirable attributes that we have come to associate with “bad” design. The program becomes fragile, rigid, unpredictable and unreusable. The open-closed principle attacks this in a very straightforward way. It says that you should design modules that never change. When requirements change, you extend the behavior of such modules by adding new code, not by changing old code that already works.

Description

Modules that conform to the open-closed principle have two primary attributes.

  1. They are “Open For Extension”.
    This means that the behavior of the module can be extended. That we can make the module behave in new and different ways as the requirements of the application change, or to meet the needs of new applications.
  2. They are “Closed for Modification”.
    The source code of such a module is inviolate. No one is allowed to make source code changes to it.

It would seem that these two attributes are at odds with each other. The normal way to extend the behavior of a module is to make changes to that module. A module that cannot be changed is normally thought to have a fixed behavior. How can these two opposing attributes be resolved?

Abstraction is the Key...

share|improve this answer
    
What a great article. Enjoyed this read thoroughly! –  Chris Nov 17 '10 at 16:12
3  
This is a good article explaining abstraction. There is a fundamental point to be considered, though, and that is was a good abstract design laid out in the first place? Many shops have a lot of legacy code that the only way to change it is "modification", not "extension". If this is the case, then one should probably work to change that, but until it does, you're stuck modifying code. –  Michael K Nov 17 '10 at 16:13
    
@Chris, cool - I also recommend the "Clean code" book by Uncle Bob if you like this sort of thing. –  Martijn Verburg Nov 17 '10 at 16:26
    
@Michael - Totally agree, it's almost like the having to refactor the code to make it testable ideal. –  Martijn Verburg Nov 17 '10 at 16:26
    
The article demonstrates the importance of abstraction very nicely. But I'm not grasping the connection between abstractions and trying never to modify modules after I write them. The abstraction means that I can modify module X without having the make modifications to module Y. But isn't the point of doing that so I can modify module X or module Y if I need to? –  Winston Ewert Nov 18 '10 at 1:34

The answer by Kate Gregory is very good, but consider a different situation where a new requirement can be satisfied by a relatively small change in the existing Invoice class. For example, lets say a new field must be added to the Invoice PDF. According to OCP, we should still create a new subclass, even if the new field could be added in the existing implementation by changing a few lines of code.

In my understanding, OCP reflects the reality of the 80's and early 90's, where projects often did not even use version control, much less had automated regression tests or the benefit of sophisticated refactoring tools. OCP was an attempt to avoid the risk of breaking code that had been manually tested and put into production. Today, we have better ways to manage the risk of breaking working software (namely, version control systems, TDD and automated testing, and refactoring tools).

share|improve this answer
1  
Yes, because in practice, it is not possible to create a class that can be extend to suit all possible futures, unless you make all methods protected (which sucks and also violates the YAGNI principle, which is much more inportant than the O/C dito). –  Martin Wickman Sep 12 '13 at 14:51
    
"According to OCP, we should still create a new subclass, even if the new field could be added in the existing implementation by changing a few lines of code.": Really? Why not add new fields or new methods? The important point is that you are only adding (extending) and not changing what is already there. –  Giorgio May 12 at 14:25
    
I think the principle makes sense when dealing with standard libraries/frameworks. You don't want to open and modify well established pieces of code. Otherwise it's all about constant refactoring and test, test, test. –  mastaBlasta May 12 at 14:39
    
@Giorgio Sure, adding new fields or methods is what I would recommend, in most cases. But that's not extension, it's "modification"; the whole point of OCP is that code should be "closed for modification" (ie, no changes to the pre-existing source file) while being "open for extension"; and extension in OCP is achieved through implementation inheritance. –  Rogério May 12 at 14:53
    
@Rogério: Why do you define the border between extension and modification at the class level? Is there a particular reason for this? I would rather set it at the method level: changing a method changes the behaviour of your application, adding a (public) method extends its interface. –  Giorgio May 12 at 16:05

Personally I think this principle should be taken with a pinch of salt. Code is organic, businesses change and code changes according to the needs of a business as time goes on.

I find it very difficult to get my head around the fact that abstraction is key. What if the abstraction was originally wrong? What if the business function has changed significantly?

This principle essentially ensures that ORIGINAL intentions and behavior of a design must never change. That probably works for those who have public API's and their clients have trouble keeping up with new releases, and some other edge-cases. However, if a company owns ALL the code, then I challenge this principle.

Having good test coverage of your code should make refactoring your code base a breeze. It means that it's okay to get stuff wrong - your tests will help guide you to a better design.

Saying that, if there aren't any tests, then this principle is sound.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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