Skip to content
aipatterns.dev

Refactoring techniqueComposing Methods

Inline Temp

Replace a temporary variable that holds a simple expression with the expression itself when the name adds nothing.

Also known as
Inline Variable

Problem

A local variable is assigned once from a simple expression and used once or twice. The name repeats what the expression already says, or the variable blocks another refactoring such as Extract Method.

Solution

Replace every reference to the variable with its expression, then delete the declaration.

Before

TypeScript
function shouldThrottle(client: ApiClient, window: RateWindow): boolean {
  const requestCount = window.countFor(client.id);
  const limit = client.plan.requestsPerMinute;
  const over = requestCount > limit;
  return over;
}

After

TypeScript
function shouldThrottle(client: ApiClient, window: RateWindow): boolean {
  return window.countFor(client.id) > client.plan.requestsPerMinute;
}

Why

  • Less to read when the expression is already self-describing.
  • Removes locals that stand in the way of extracting or moving code.
  • Fewer names to keep in sync during later edits.

Steps

  1. Confirm the variable is assigned exactly once. Mark it const and compile to prove it.
  2. Confirm the right-hand side has no side effects and returns the same value each time it is read in this scope.
  3. Replace the first reference with the expression. Run the tests.
  4. Replace the remaining references, then delete the declaration. Run the tests.

Watch out

  • Don't inline when the expression is expensive (a query, a network call, a large loop) and the variable is read several times. You would repeat the work.
  • Don't inline when the value can change between reads, for example Date.now() or a mutable field another call updates.
  • Don't inline when the name explains something the expression does not. That variable is doing the job of Extract Variable, the inverse technique.
  • If the expression is long and used in several functions, Replace Temp with Query is a better destination.

Agent checklist

  • The variable had a single assignment.
  • The expression is pure and cheap, or is read only once.
  • No reader loses information that the variable name carried.
  • Tests pass.

Treats these smells

See also

Original writing and examples. Topic coverage follows Refactoring.Guru, which explains this topic with its own illustrations.