OCP — The Open-Closed Principle

Oliver Jumpertz
3 min readJan 23, 2022

The Open-Closed principle is a part of SOLID, a mnemonic acronym that bundles a total of 5 design principles.

It is often associated with clean code.

But what exactly is it, is it important to you, should you even care?

What does it state?

The statement it sets is pretty straight-forward:

Software entities should be open for extension, but closed for modification”.

And entities can be a lot:

  • classes
  • modules
  • functions
  • etc.

To put it another way: Entities should allow their behavior to be changed without the need to modify their own source code.

An Example

Take a look at the example below to get an idea of a use case for the open-closed principle.

Please keep the following in mind: This is only a very basic example, and there are of course other examples that would also present what this one does well.

const allowedRoles = [“DevOps”, “SRE”];export function isAllowedToDeployChanges(user) {
return allowedRoles.includes(user.role);
}

--

--