Open-Closed Principle

'A class should be open for extension closed for modification.'

The above principle explains that a class once defined should not be changed(closed for modification). This is because it may impact other parts of application.
Hence, if modification is needed, that class behaviour should be extended and modification should be done. (open for extension)

Consider a scenario where area of a shape(like rectangle, square, circle) is calculated within Main class. Now addition of any new shape will lead to change in Main class. This concludes that the Shape is tightly coupled with Main class.

In order to avoid this Shape should be inherited by diff Shape classes like Rect, Triangle, Circle implementing the behaviour of calculating area() and Main class should be loosely coupled by using Shape.area() (as Triangle, Rectangle are Shape).
Hence, Shape interface is contract between its concrete classes and Main class. This allows us to add new shape class without any impact on existing functionality. (open for extension) and we do not have to modify Main class (closed for modification)

From the above, we can say that if addition of new subclass leads to code change that means Open-Closed Principle is been violated.

Comments

Popular posts from this blog

@Overrride annotation introduced in Java1.5

Liskov Substitution Principle (LSP)

Interface Segregation Principle