Parameterize Method

Several methods do similar things but with different values.

“Several methods do similar things but with different internal values, numbers, or operations.”

Make it generic.

graph LR
    A[fivePercent()] -->|Refactoring| B[raises(0.05)]
    C[tenPercent()] -->  B

When to apply (Smells)

  • Duplication: raise5Percent(), raise10Percent().

Motivation

  • DRY: One method to rule them all.

Mechanics (Steps)

  1. Create a parameterized method.
  2. Replace specific methods with calls to the parameterized one.
  3. Delete specific methods.

Explanation

Problem

fivePercent(), tenPercent().

Solution

percent(arg).

Pros and Cons

Pros Cons
  • Less duplication
  • None
  • Code example

    Typescript

    Before

    After

    PHP

    Before

    After