Replace Parameter with Explicit Methods

A method runs different code depending on the value of an enumerated parameter.

“You have a method that runs different code depending on the values of an enumerated parameter.”

Make it specific.

graph LR
    A[setValue(name, val)] -->|Refactoring| B[setName(val)]

When to apply (Smells)

  • Switch Statements: Method body assumes behavior based on a flag.

Motivation

  • Clarity: turnOn() is clearer than setSwitch(ON).

Mechanics (Steps)

  1. Create a method for each value of the parameter.
  2. Move the corresponding logic to the new methods.
  3. Remove the old method.

Explanation

Problem

setValue("height", 10)

Solution

setHeight(10)

Pros and Cons

Pros Cons
  • Clarity
  • More methods
  • Comparison

    • Inverse Refactoring: Parameterize Method.

    Code example

    Typescript

    Before

    After

    PHP

    Before

    After