Show in graph

Software → Software Design

Composition

The practice of building behavior by combining smaller objects or modules rather than relying mainly on inheritance.

Motivation

Composition solves the problem of inheritance hierarchies that become rigid and fragile. Instead of forcing behavior into a class tree, objects can be built by combining focused collaborators.

Where it fits

Composition belongs to software design and object-oriented programming. It supports modularity, testability, and dependency injection.

Code example
Bad example
Python
class EmailReceiptOrderService(PaymentOrderService):  def checkout(self, order):      self.charge(order)      self.save(order)      self.send_email(order)
Good example
Python
class OrderService:  def __init__(self, payment, repository, notifier):      self.payment = payment      self.repository = repository      self.notifier = notifier  def checkout(self, order):      self.payment.charge(order.total)      self.repository.save(order)      self.notifier.confirm(order)

Common mistakes

  • Replacing every inheritance relationship even when subtyping is valid.
  • Passing too many collaborators into one object because responsibilities are still unclear.