Replace Delegation with Inheritance

You are using delegation and are writing many simple delegating methods to the entire interface of the delegate.

“You are using delegation and are writing many simple delegating methods.”

If it really IS-A, use inheritance.

graph LR
    A[Class A] -->|Delegates| B[Class B]
    A -->|Refactoring| B
    A -.->|Inherits| B

When to apply (Smells)

  • Method Explosion: You are forwarding every method.

Motivation

  • Simplicity: extends gives you all methods for free.

Mechanics (Steps)

  1. Make the delegating class inherit from the delegate.
  2. Remove the delegate field.

Explanation

Problem

Employee contains Person and delegates getName, getAddress, getPhone, etc.

Solution

Employee extends Person.

Pros and Cons

Pros Cons
  • Less boilerplate
  • Tight coupling
  • Comparison

    • Inverse Refactoring: Replace Inheritance with Delegation.

    Code example

    Typescript

    Before

    After

    PHP

    Before

    After