Skip to main content

Definition of Open/Closed Principle

Open/Closed Principle (OCP)

Definition

Formal Definition The Open/Closed Principle (OCP) states that software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. This means that the behavior of a module can be extended without modifying its source code.

Simplified Definition In simpler terms, the Open/Closed Principle means you can add new features or behaviors to a class or module without changing its existing code. You achieve this by writing new code that interacts with the existing code through well-defined interfaces.

Analogy Think of a smartphone. The phone's hardware and core operating system are "closed for modification" – you can't change them without risking damage or voiding the warranty. However, the phone is "open for extension" because you can install new apps that add functionality without altering the phone's core system. Similarly, in software design, you should be able to add new features by adding new code rather than changing existing, tested, and stable code.