80 likes | 233 Views
OO Design Principles. Principle 2. The Open-Closed Principle: Software Entities Should be Open For Extension, Yet Closed For Modification. Open-Closed Principle. The open-closed principle (OCP) says that we should attempt to design modules that never need to be changed.
E N D
OO Design Principles lecture 08, OO Design Principle
Principle 2 • The Open-Closed Principle: Software Entities Should be Open For Extension, Yet Closed For Modification lecture 08, OO Design Principle
Open-Closed Principle • The open-closed principle (OCP) says that we should attempt to design modules that never need to be changed. • To extend the behavior of the system, we need to add code. We do not modify old code • Modules that conform to OCP meet two criteria: • Open for Extension – the behavior of the module can be extended to meet new requirements • Closed for modification – the source code of the module is not allowed to change • How can we do this • Inheritance • Abstraction • Polymorphism • Interface lecture 08, OO Design Principle
Open-Closed Principle • It is not possible to have all the methods of a software system satisfy the OCP, but we should minimize the number of modules that do not satisfy it. • The OCP is really the heart of OO design • Conformance to this principle yields the greatest of reusability and maintainability. lecture 08, OO Design Principle
OCP Example • In the Video Store example, we use inheritance to represent the different categories of a Movie. • When a new category of a movie comes in, you don’t need to modify the existing code. Just add another subclass of class Movie. • Without a subclass, what construct should be used to support different categories of a Movie class? lecture 08, OO Design Principle