Architectural Patterns
上QQ阅读APP看书,第一时间看更新

Open and close principle – SOLID

The open and close principle of OO programming suggests that the OO software entities such as classes, methods or functions, and modules, should be open for extensions, but closed for any modifications.

Imagine a class that you never need to change, and any new functionality gets added only by adding new methods or subclasses, or by reusing the existing code, and so we can prevent any new defects to the existing code or functionality.

The preceding class diagram shows the application of the open and close principle on the Account class and its subclasses. The account can be any type, savings or current. A SavingsAccount may categorize as GeneralAccount, KidsAccount, and so on, so we can enforce that Account and other subclasses are available for Enhancements but closed for modifications.

The open and close principle brings benefits of no changes to the code, no introduction of any new defects but perhaps a disadvantage that the existing defects never get addressed as well.