Skip to content

Open / Closed Principle [OCP]

Software entities (classes, modules, functions, etc) should be open for extension but closed for modification.

Should be possible to change the behaviour of a method without editting its source code.

open to extension closed to modification
new behaviour can be added in future changes to source/binary code are not required
code that is closed to extension has fixed behaviour the only way to change behaviour of code that is closed to extension is to modify the code itself.

switch statements notoriously break the open/closed principle, e.g.

switch (policy.Type) {
    case PolicyType.Auto: ...
    case PolicyType.Life: ...
}

Also Enum can be a bit of a code smell.

OCP is a balancing act between abstraction and concretion.

Predicting Future Change

OCP tends to be applied retrospectively - once you know how things are likely to change.

  • start by coding something concrete
  • modify code the first few times as requirements change
  • by the third modification consider making the code open to expansion.

Typical Approaches to OCP

  • parameters
  • inheritance
  • composition/injection

It's preferable to implement new features in new classes. New classes aren't coupled in any way to the existing system.

OCP also applies to; packages & libraries, microservices.

Articles

https://bit.ly/2LSXOuo
Uncle Bob on OCP
Jon Skeet on OCP