Software Design Principles →

Open-Closed Principle

What

🏆 Can explain open-closed principle (OCP)

While it is possible to isolate the functionalities of a software system into modules, there is no way to remove interaction between modules. When modules interact with each other, coupling naturally increases. Consequently, it is harder to localize any changes to the software system. In 1988, Bertrand Meyer proposed a guiding principle to alleviate this problem. The principle, known as the open-closed principle, states: “A module should be open for extension but closed for modification”. That is, modules should be written so that they can be extended, without requiring them to be modified. In other words, changing what the modules do without changing the source code of the modules.

In object-oriented programming, these two seemingly opposing requirements can be achieved in various ways. This often requires separating the specification (interface) of a module from its implementation.

Example:

The behavior of the CommandQueue class can be altered by adding more concrete Command subclasses. For example, by including a Delete class alongside List, Sort, and Reset, the CommandQueue can now perform delete commands without modifying its code at all. Indeed, its behavior was extended without having to open up and modify its code. Hence, it was open to extensions, but closed to modification.

The behavior of a Java generic class can be altered by passing it a different class as a parameter. In the code below, the ArrayList class behaves as a container of Students in one instance and as a container of Admin objects in the other instance, without having to change its code. That is, the behavior of the ArrayList class is extended without modifying its code.

ArrayList students = new ArrayList< Student >();
ArrayList admins = new ArrayList< Admin >();  	

Which of these is closest to the meaning of the open-closed principle?

  • a. We should be able to change a software module’s behavior without modifying its code.
  • b. A software module should remain open to modification as long as possible.
  • c. A software module should be either open to modification and closed to extension.
  • d. Open source software rocks. Closed source software sucks.
  • a. We should be able to change a software module’s behavior without modifying its code.
  • b. A software module should remain open to modification as long as possible.
  • c. A software module should be either open to modification and closed to extension.
  • d. Open source software rocks. Closed source software sucks.

Explanation: Please refer the handout for the definition of OCP.