Inline Temp

Replace references to a temp variable with the expression itself.

“You have a temp that is assigned to once with a simple expression, and the temp is getting in the way of other refactorings.”

Remove unnecessary variables.

graph LR
    A[Named Variable] -->|Refactoring| B[Expression]

When to apply (Smells)

  • Temp blocks Extract Method: A variable is used only once and prevents easy extraction of surrounding method logic.

Motivation

  • Sometimes variables don’t add clarity, they just take up space.
  • Prerequisite for Replace Temp with Query.

Mechanics (Steps)

  1. Find all references to the temp.
  2. Replace them with the assigned expression.
  3. Remove the declaration.

Explanation

Problem

You have a temp variable that is assigned the result of a simple expression and effectively adds nothing to readability.

Solution

Replace references to the variable with the expression itself.

Real world analogy

If you write down “Key Code = 1234” and then define “Secret = Key Code”, you might as just say “Secret = 1234”.

Pros and Cons

Pros Cons
  • Less lines of code
  • Can repeat expensive calculations (if not careful)
  • Comparison

    • Inverse Refactoring: Extract Variable.

    Code example

    Typescript

    Before

    After

    PHP

    Before

    After