Card 08/ 08

RecapDifficulty: Intermediate1 min

Recap: Open/Closed

New behaviour as new code, once the second case shows where the seam belongs.

The open/closed principle lets you add behaviour without editing code that works.

  • Open for extension, closed for modification. New cases are new classes; existing classes are not opened.
  • The extension point is an abstraction the stable code depends on, such as PaymentMethod or Shape. Meyer's 1988 form used inheritance; Martin's 1996 form uses interfaces and polymorphism.
  • The symptom is a type conditional that grows with every case, often repeated across several functions.
  • The refactor pins the output, introduces the interface, moves each branch into a class, points the caller at the interface, and deletes the conditional last.
  • Libraries do it with supplied objects: a list of discount rules, or the default function passed to json.dumps.
  • Do not build extension points in advance. Close code against changes you have seen, and wait for the second case unless the business already expects more.