Skip to content

Replace Temp with Query: Turn Local Variables into Methods

Learn how to replace a temporary variable with a method that computes it, so the logic can be reused, named and tested.

7 min readRefactoring

Replace Temp with Query takes a local variable that holds the result of an expression and moves that expression into its own method. Every place that read the variable now calls the method. The refactoring is small, but it often comes before larger ones. A temp is visible only inside one method. A query method is visible to the whole class. Once a calculation lives in a method, other methods can reuse it, you can test it directly, and the long method that held it becomes easier to split. In interviews this comes up when you are asked to clean up a long function or explain how you would prepare code for Extract Method. Knowing when a temp should stay a temp matters just as much.

The problem

A situation where the obvious design starts to hurt.

Parcelwise, an invented courier startup, prices parcels by chargeable weight. That is the greater of the actual weight and the volumetric weight, which is length times width times height in centimetres divided by 5000. The Parcel class computes these two figures as local variables inside shippingFee, and then computes them again inside isOversize, because a temp in one method cannot be seen from another.

The two copies already have to be kept in sync by hand. If the divisor changes from 5000 to 4000 for a new carrier contract, someone has to find both places. The long method also mixes how chargeable weight is derived with how the fee is tiered, which makes it hard to read and hard to test either part on its own.

Before and after

The same code, before and after the change.

Before

export class Parcel {
  constructor(
    private readonly lengthCm: number,
    private readonly widthCm: number,
    private readonly heightCm: number,
    private readonly actualKg: number,
  ) {}

  shippingFee(): number {
    const volumetricKg = (this.lengthCm * this.widthCm * this.heightCm) / 5000;
    const chargeableKg = Math.max(this.actualKg, volumetricKg);
    if (chargeableKg <= 2) {
      return 6.5;
    }
    return 6.5 + (chargeableKg - 2) * 1.8;
  }

  isOversize(): boolean {
    const volumetricKg = (this.lengthCm * this.widthCm * this.heightCm) / 5000;
    const chargeableKg = Math.max(this.actualKg, volumetricKg);
    return chargeableKg > 30;
  }
}

const box = new Parcel(40, 30, 20, 3);
console.log(box.shippingFee(), box.isOversize()); // 13.7 false

After

export class Parcel {
  constructor(
    private readonly lengthCm: number,
    private readonly widthCm: number,
    private readonly heightCm: number,
    private readonly actualKg: number,
  ) {}

  shippingFee(): number {
    if (this.chargeableKg() <= 2) {
      return 6.5;
    }
    return 6.5 + (this.chargeableKg() - 2) * 1.8;
  }

  isOversize(): boolean {
    return this.chargeableKg() > 30;
  }

  private volumetricKg(): number {
    return (this.lengthCm * this.widthCm * this.heightCm) / 5000;
  }

  private chargeableKg(): number {
    return Math.max(this.actualKg, this.volumetricKg());
  }
}

const box = new Parcel(40, 30, 20, 3);
console.log(box.shippingFee(), box.isOversize()); // 13.7 false

Why it's worth it

What the change buys you.

A temp gives a name to a value, which is good, but the name dies at the end of the method. A query method keeps the name and makes it available to the whole class. In the Parcelwise example the volumetric formula now exists once, so a change to the divisor is a one-line edit, and isOversize no longer repeats logic it has no business owning.

The remaining methods also read closer to the business rule. shippingFee is now only about fee tiers, and the rule for chargeable weight sits in a method whose name says exactly what it returns. That separation makes further refactoring cheap: you could move the tiers into a pricing table or extract a Dimensions value object without touching the weight logic.

The trade-off is that the expression is evaluated each time it is called. chargeableKg is now computed twice in shippingFee. For a few multiplications that cost is negligible, and the method has no side effects, so calling it twice gives the same answer. If a query becomes genuinely expensive, cache it deliberately rather than keeping a temp for speed by default.

  • The calculation lives in one place, so a rule change touches one method instead of every method that copied it.
  • Other methods in the class can reuse the value without recomputing it by hand.
  • Long methods get shorter and focus on a single decision, which makes Extract Method easier later.
  • The derived value can be tested on its own once it has a name and a home.

Careful with

  • Only replace temps that are assigned once from an expression with no side effects. A temp that accumulates in a loop or is reassigned needs Split Temporary Variable first.
  • A temp captures a value at one moment. If the object's state changes between assignment and use, a query returns the new value, which can silently change behaviour.
  • If the expression is expensive, such as a database call or a large loop, repeated calls can hurt. Measure, and add explicit caching if needed rather than keeping duplicated temps.
  • Do not turn every temp into a method. A temp used once, close to where it is defined, inside a short method is often clearest as it is.

Step by step

Small, safe steps, with the tests passing after each.

  1. Make sure the tests cover shippingFee and isOversize, including a parcel where actual weight wins, one where volumetric weight wins and one at the 2 kg boundary.

  2. Check that volumetricKg is assigned exactly once and that computing it has no side effects. If it were reassigned later, split the variable first.

  3. Extract the right-hand side of volumetricKg into a private method volumetricKg() and change the temp's initialiser to call it. Run the tests.

  4. Replace every read of the volumetricKg temp in shippingFee with a call to the method, delete the temp declaration and run the tests.

  5. Repeat for chargeableKg: extract a private chargeableKg() method that calls volumetricKg(), replace the reads, delete the temp and run the tests.

  6. In isOversize, replace both duplicated temps with a call to chargeableKg(), delete the copies and run the tests.

  7. Review the names and visibility of the new methods. Keep them private unless another class genuinely needs them.

Smells it removes

Smells this refactoring helps remove.

Common questions

Short answers to the usual doubts.

Doesn't calling the method twice make the code slower?

Slightly, in theory. For cheap arithmetic like the volumetric weight the difference is not measurable in practice. If profiling later shows a query is a hot spot, you can memoise it in one place, which is easier than optimising scattered temps.

How is this different from Extract Method?

Replace Temp with Query is a focused use of Extract Method where the extracted code is the expression that initialises a variable, and the variable is then removed. It is often done as preparation for extracting larger chunks of a long method, because temps tie code fragments together.

Why did the Python version use a property instead of a method?

In Python a read-only derived value is commonly exposed as a property, so callers read it like an attribute. A plain method would work equally well. The behaviour is the same: the expression is evaluated on every access.

What should I do with a temp that is assigned inside a loop?

Leave it for now. A loop accumulator is not a simple expression you can move into a query. Consider Split Loop or Extract Method on the whole loop first, then the result of that method can replace the temp.

How would I explain this refactoring in an interview?

Say what the temp was blocking, such as duplication across methods or a long method that is hard to split, then describe the safe steps: confirm single assignment and no side effects, extract the expression, replace the reads, delete the temp and run tests after each change. Mention the trade-off around repeated evaluation.

Next guide4 of 5 · Techniques: organizing dataSplit Variable: One Name per PurposeRead the next one