Solid Principle #2: The Open/closed Principle
The open/closed principle states that “software entities (classes, modules, function, etc.) should be open for extension, but closed for modification”.
The definition of the principle suggests we should use always object abstractions. This means that the existing interface is closed to modifications and new implementations must implement that interface. So, we should create new classes (extension), and not change the current class already implemented.
Consider the following example. We want to create an application for a store. The store sells items of different costs. Each item has a fixed cost of 60 cents.
Now to make this more complicated. We now have two items in our store that have different prices. The coffee costs 0.60 cents and the cake costs 0.90 cents.
But what happens if we want to sell more item types? We keep changing the same class every time to extend our features.
Each time we are extending, we are modifying the current class. Abstraction is key!
Now, each time we want to extend our store with new items, we just need to create a new item, that implements an interface that implements the method cost()
.
Conclusion
Abstraction is key in the open/closed principle. We should always try to abstract our code in order to not modify it every time we want to extend something. In this case, we were adding new items to the store and changing the same method every time.
In the last example we have shown that if the item implements an interface with a method cost()
it will respect this principle, because we abstract the cost of the item which makes adding more items of different costs simpler.
Bibliography
http://www.objectmentor.com/resources/articles/ocp.pdf
http://joelabrahamsson.com/a-simple-example-of-the-openclosed-principle/
http://en.wikipedia.org/wiki/Open/closed_principle