Friday, November 22, 2013

Open Closed Principle

The Open/Closed Principle states that a class or module should be open to extension but closed to modification.

This means that you want to build your classes or API's in ways that present interfaces to the consuming client.  Add new code, don't modify current code.  What's that?  You have a defect?  How could you ever follow this core tenant of the SOLID principles without modifying the current code?  You may not be able to.  Bertrand Meyer (the man who defined the Open Closed Principle) even claims that you will have to be open to modification for the sake of fixing defects.  The thing to keep in mind is that the defect you are about to "fix" may be modifying a dependency in code somewhere else.  This is why this principle is so key.  It prevents you from being on the wrong end of "Does he even know what the heck he's doing?"

There is power in this principle, but its power is much deeper.  This principle is best executed through abstractions.  Abstractions, while sometimes mind-bending, allow for greater flexibility with changes to the system.  It becomes easier to add another widget if that widget behaves like other, already defined widgets.

Want to read more about the Open/Closed Principle from the man who coined SOLID (Uncle Bob)?  Check out this document.

No comments:

Post a Comment