extract-variable
Give a name to a complex expression by assigning it to a well-named variable.
SKILL.mdskills/code-quality/extract-variable/SKILL.md
GitHubExtract Variable
Complex or repeated expressions are hard to read. Assign them to a descriptive variable that explains intent.
When to Use
- Expression is complex or hard to understand at a glance
- Same expression is used in multiple places within a method
- A sub-expression represents a meaningful concept in the domain
- Boolean conditions with many operators
How to Apply
- Identify the expression to extract
- Declare an immutable variable (
const/final) and assign the expression - Name the variable after the concept it represents, not its type
- Replace occurrences of the expression with the variable
- Run tests
Example
// Before
if (order.quantity > 100 && order.itemPrice > 50 && order.employee.seniorityYears > 5) {
applyDiscount(order);
}
// After
const isLargeOrder = order.quantity > 100;
const isHighValue = order.itemPrice > 50;
const isSeniorEmployee = order.employee.seniorityYears > 5;
if (isLargeOrder && isHighValue && isSeniorEmployee) {
applyDiscount(order);
}