Programming Search⌘K

Techniquecore

Replace function with command

Also called replace method with method object.

Turn a long or complex function into an object whose fields hold the arguments and the temporary values, and whose one method runs the work.

Family
refactoring
Intent
Give a complex function room to be split up.
Also called
Replace Method with Method Object

Purpose

A long function with many local variables is hard to split. Each piece that Extract Function takes out needs the locals as parameters, and the new functions get long parameter lists.

Replace function with command moves the function into its own class. The arguments become fields, set in the constructor. The body moves to one method, often called execute. The local variables can then become fields too, and each piece of the body can become a method with no parameters. The catalogue card turns function score(candidate, medicalExam, scoringGuide) into class Scorer, with the three arguments as fields, and result and healthLevel as fields that execute sets.1

The object is a command in the sense of the Command pattern: an object that holds one request. The card names the old name, Replace Method with Method Object, and the inverse, Replace Command with Function.1

Steps

  1. Make an empty class. Name it after the function.
  2. Move the function into the class as one method, execute. Keep the old function and make it call the class, so that the callers do not change.
  3. Make a field for each argument, and set it in the constructor. Change execute to read the fields.
  4. Test.
  5. Make the local variables fields, one at a time, and test after each one.
  6. Now use Extract Function on the body. The new methods read the fields, so they need no parameters. See Extract Function.

Example

score gives points to a candidate. The body has three parts, and each one changes the local result. As a command, each part becomes a method.

import assert from "node:assert/strict";

const candidate = { originState: "CA" };
const medicalExam = { isSmoker: true };
const scoringGuide = { stateWithLowCertification: (s) => s === "CA" };

function score(candidate, medicalExam, scoringGuide) {
  let result = 0;
  let healthLevel = 0;
  if (medicalExam.isSmoker) { healthLevel += 10; }
  let certificationGrade = "regular";
  if (scoringGuide.stateWithLowCertification(candidate.originState)) {
    certificationGrade = "low";
    result -= 5;
  }
  result -= Math.max(healthLevel - 5, 0);
  return { result, certificationGrade };
}

class Scorer {
  constructor(candidate, medicalExam, scoringGuide) {
    this._candidate = candidate;
    this._medicalExam = medicalExam;
    this._scoringGuide = scoringGuide;
  }
  execute() {
    this._result = 0;
    this._healthLevel = 0;
    this.scoreSmoking();
    this.scoreCertification();
    this._result -= Math.max(this._healthLevel - 5, 0);
    return { result: this._result, certificationGrade: this._certificationGrade };
  }
  scoreSmoking() {
    if (this._medicalExam.isSmoker) { this._healthLevel += 10; }
  }
  scoreCertification() {
    this._certificationGrade = "regular";
    if (this._scoringGuide.stateWithLowCertification(this._candidate.originState)) {
      this._certificationGrade = "low";
      this._result -= 5;
    }
  }
}

const after = new Scorer(candidate, medicalExam, scoringGuide).execute();
assert.deepEqual(after, score(candidate, medicalExam, scoringGuide));
console.log(after);
Output
{ result: -10, certificationGrade: 'low' }

The rules of the score are made up for the example. The shape follows the catalogue card.1

Language What the example shows
JavaScript score turned into class Scorer with execute, as above
Python the same class; a nested function with nonlocal is shown as the lighter way to share the locals
Go a scorer struct with an execute method; the helper methods take a pointer receiver because they change the fields
PythonGitHub
def score(candidate: dict, medical_exam: dict, scoring_guide) -> tuple[int, str]:
    result = 0
    health_level = 0
    if medical_exam["is_smoker"]:
        health_level += 10
    certification_grade = "regular"
    if scoring_guide(candidate["origin_state"]):
        certification_grade = "low"
        result -= 5
    result -= max(health_level - 5, 0)
    return result, certification_grade


class Scorer:
    def __init__(self, candidate: dict, medical_exam: dict, scoring_guide) -> None:
        self._candidate = candidate
        self._medical_exam = medical_exam
        self._scoring_guide = scoring_guide

    def execute(self) -> tuple[int, str]:
        self._result = 0
        self._health_level = 0
        self._score_smoking()
        self._score_certification()
        self._result -= max(self._health_level - 5, 0)
        return self._result, self._certification_grade

    def _score_smoking(self) -> None:
        if self._medical_exam["is_smoker"]:
            self._health_level += 10

    def _score_certification(self) -> None:
        self._certification_grade = "regular"
        if self._scoring_guide(self._candidate["origin_state"]):
            self._certification_grade = "low"
            self._result -= 5


# The lighter way: nested functions that share the locals with nonlocal.
def score_nested(candidate: dict, medical_exam: dict, scoring_guide) -> tuple[int, str]:
    result = 0
    health_level = 0

    def score_smoking() -> None:
        nonlocal health_level
        if medical_exam["is_smoker"]:
            health_level += 10

    score_smoking()
    grade = "low" if scoring_guide(candidate["origin_state"]) else "regular"
    result -= 5 if grade == "low" else 0
    return result - max(health_level - 5, 0), grade


args = ({"origin_state": "CA"}, {"is_smoker": True}, lambda s: s == "CA")
assert Scorer(*args).execute() == score(*args) == score_nested(*args)
print(Scorer(*args).execute())
Output
(-10, 'low')
package main

import "fmt"

type Candidate struct{ OriginState string }
type MedicalExam struct{ IsSmoker bool }
type ScoringGuide struct{ LowCertification map[string]bool }

func score(c Candidate, m MedicalExam, g ScoringGuide) (int, string) {
	result, healthLevel := 0, 0
	if m.IsSmoker {
		healthLevel += 10
	}
	grade := "regular"
	if g.LowCertification[c.OriginState] {
		grade = "low"
		result -= 5
	}
	result -= max(healthLevel-5, 0)
	return result, grade
}

type scorer struct {
	candidate   Candidate
	medicalExam MedicalExam
	guide       ScoringGuide
	result      int
	healthLevel int
	grade       string
}

func (s *scorer) execute() (int, string) {
	s.result, s.healthLevel = 0, 0
	s.scoreSmoking()
	s.scoreCertification()
	s.result -= max(s.healthLevel-5, 0)
	return s.result, s.grade
}

func (s *scorer) scoreSmoking() {
	if s.medicalExam.IsSmoker {
		s.healthLevel += 10
	}
}

func (s *scorer) scoreCertification() {
	s.grade = "regular"
	if s.guide.LowCertification[s.candidate.OriginState] {
		s.grade = "low"
		s.result -= 5
	}
}

func main() {
	c, m, g := Candidate{"CA"}, MedicalExam{true}, ScoringGuide{map[string]bool{"CA": true}}
	r1, g1 := score(c, m, g)
	s := &scorer{candidate: c, medicalExam: m, guide: g}
	r2, g2 := s.execute()
	if r1 != r2 || g1 != g2 {
		panic("mismatch")
	}
	fmt.Println(r2, g2)
}
Output
-10 low

When to use

  • A long function that is hard to split. The locals become fields, so the extracted pieces need no parameters. See Long function.
  • The call needs more than a call. A command object can be stored, put in a queue, logged, or undone. It can also have methods to set options before it runs.
  • Subclasses must change one step. A command can have a subclass that overrides one of its methods.

Pitfalls

More code. A class with a constructor, fields and execute is longer than a function. Use the refactoring only when the function needs it. Most functions do not.

Fields that live too long. The temporary values now live as long as the object. If the same object runs twice, an old value can stay in a field. Set each temporary field at the start of execute, as the example does.

First-class functions. In a language with closures, a nested function can often share the locals with less code. The refactoring is most useful in languages without them, or when the command must be stored or changed.

Tools that do it

IDEs do not have one action for this refactoring under this name. The steps use Extract Function, Change Function Declaration and the field and variable refactorings of the IDE.

The catalogue lists Replace Function with Command in the first edition, the second edition and the Ruby edition, and its inverse in the second edition only. Both have the tag refactoring-apis.2 In the second edition it is in Chapter 11, Refactoring APIs.3

References

  1. Martin Fowler, Catalog of Refactorings, Replace Function with Command, the entry, the score and Scorer sketch; inverse of Replace Command with Function; aliases Replace Method with Method Object
  2. Martin Fowler, Catalog of Refactorings, index, the entries replaceFunctionWithCommand and replaceCommandWithFunction, their books and tags
  3. Martin Fowler, Refactoring, Improving the Design of Existing Code, second edition, Addison-Wesley, 2018, Chapter 11, Refactoring APIs, Replace Function with Command

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/4QMAXW/text.yaml