Show in graph

Software → Software Design

OCP

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

Motivation

OCP solves the problem of changing stable code every time a new case is added. If each new discount, payment method, or notification type requires editing the same central class, that class becomes risky to modify.

Where it fits

OCP belongs to SOLID and software design. It often uses polymorphism, strategy objects, and dependency injection.

Code example
Bad example
Python
class DiscountCalculator:  def discount(self, order, customer_type):      if customer_type == "standard":          return 0      if customer_type == "vip":          return order.total * 0.10      if customer_type == "partner":          return order.total * 0.15      return 0
Good example
Python
class DiscountPolicy:  def discount(self, order):      raise NotImplementedErrorclass VipDiscount(DiscountPolicy):  def discount(self, order):      return order.total * 0.10class PartnerDiscount(DiscountPolicy):  def discount(self, order):      return order.total * 0.15class DiscountCalculator:  def discount(self, order, policy):      return policy.discount(order)

Common mistakes

  • Adding abstractions before there is real variation.
  • Thinking OCP means code can never be modified. Stable code should be protected; evolving code can still change.