Extract Interface

Several clients use the same subset of a class’s interface.

“Several clients use the same subset of a class’s interface, or two classes have part of their interfaces in common.”

Decouple implementation from contract.

graph LR
    A[Class A] -->|Refactoring| B[<Interface I>]
    A -.->|Implements| B

When to apply (Smells)

  • Coupling: Clients depend on the whole class when they only need a few methods.

Motivation

  • De-coupling: Clients can depend on Billable instead of Employee.

Mechanics (Steps)

  1. Create an interface.
  2. Make the class implement it.
  3. Change type annotations in clients to use the interface.

Explanation

Problem

Company depends on Employee but only uses getRate() and hasSpecialSkill().

Solution

Create Billable interface with getRate() and hasSpecialSkill().

Pros and Cons

Pros Cons
  • Loose Coupling
  • More artifacts
  • Code example

    Typescript

    Before

    After

    PHP

    Before

    After