Object-oriented – Clarify the Open/Closed Principle

object-oriented

As I have had it explained, the open/closed 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.

Best Answer

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.