extract-variable

Apply Extract Variable: name a complex or repeated expression with a local variable.

nickgerrer/refactoring-guru-skills2 installsMITSynced Aug 26

Works with

Claude CodeCursorCodex CLIGitHub CopilotGemini CLI
---
name: extract-variable
description: Apply Extract Variable: name a complex or repeated expression with a local variable.
license: MIT
---

# Extract Variable (refactoring)

Replace an expression with a named variable that holds the expression's value. Comply with `PRINCIPLES.md`.

Often invoked by: `long-method` (when names would help readability), `decompose-conditional`.

## Inputs

```yaml
target: path/to/Class.ext:line       # required; the location of the expression
expression: <the expression>         # required (informal)
variable_name: meaningfulName        # required
```

## Pre flight (in addition to PRINCIPLES.md)

1. Read the target method.
2. Confirm the expression has no side effects, or that extracting once preserves order.
3. Identify all occurrences if you want to deduplicate.

## Mechanics

1. Insert a `$variable = <expression>;` line before the first use.
2. Replace each occurrence of the expression with `$variable`.
3. Run tests; report.

## Safety rules

* Expression has side effects and appears in multiple places: extracting changes semantics. Surface.
* Expression is large and used once: extraction may not add value; consider `extract-method` instead.
* Single-file change; multi-file impact unusual.

## Example (PHP)

Before.

```php
return $order->subtotal() * (1 - $order->customer()->loyaltyTier()->discountRate());
```

After.

```php
$discountRate = $order->customer()->loyaltyTier()->discountRate();
return $order->subtotal() * (1 - $discountRate);
```

## Pitfalls and when to skip

| Pitfall | Skip in favor of |
|---|---|
| Expression has side effects | Surface and reconsider |
| Expression is trivial | Skip; inline is clearer |
| Expression deserves a method, not a variable | `extract-method` or `replace-temp-with-query` |

## Output

Post-edit report per `PRINCIPLES.md`. Stop reasons.

* `side-effects`: expression mutates state.
* `read-failed`: target could not be read.
* `tests-failed`: tests ran and failed after the edit.

More Accessibility skills

← All Accessibility skills

Check your AI visibility

One URL in, a 0–100 score and the exact fixes out.

RUN THE CHECK

Browse all the tools

15 tools across six categories
13 of them never send your data anywhere

Free · No signup · No trial clock

SEE THE DIRECTORY