Split Temporary Variable

Split a variable that serves two different purposes into two variables.

“You have a temporary variable assigned to more than once, but is not a loop variable nor a collecting temporary variable.”

One variable should have one responsibility.

graph LR
    A[Reused Temp] -->|Refactoring| B[Two Distinct Temps]

When to apply (Smells)

  • Confusion: A variable named temp holds a height, then later holds a width.
  • Assignment: Variable is assigned to multiple times with completely different values.

Motivation

  • Readability: Each variable should explain its specific purpose.
  • Maintenance: Easier to verify and debug.

Mechanics (Steps)

  1. Change the name of the variable at the first assignment.
  2. If the variable is const (or immutable), good.
  3. Change references up to the second assignment.
  4. Repeat for subsequent assignments.

Explanation

Problem

You have a temporary variable that is assigned to more than once.

Solution

Use a different temporary variable for each assignment.

Real world analogy

Using the same labeled jar for “Sugar” and then later for “Salt”. It’s confusing. Use two jars.

Pros and Cons

Pros Cons
  • Clarity
  • Prevents accidental bugs
  • More memory (Variables live longer)? V8 handles this fine.
  • Comparison

    • Related: Remove Assignments to Parameters.

    Code example

    Typescript

    Before

    After

    PHP

    Before

    After