Localizing Variables
БесплатноБез исполняемых скриптовНе проверенDeclare variables in smallest possible scope, initialize close to first use, minimize span and live time
Об этом скилле
Localizing Variables
Overview
The Principle of Proximity: Keep related actions together. Declare variables in the smallest scope possible, initialize them close to where they're first used, and keep all references to a variable close together.
Core principle: Minimize the window of vulnerability. The smaller the scope and the closer the references, the less can go wrong and the easier code is to understand.
Goal: Reduce what you must keep in mind at any one time.
When to Use
Apply to every variable you declare:
- When declaring variables
- When initializing variables
- When reviewing code with scattered variable usage
- When refactoring to improve clarity
Warning signs:
- Variables declared at top of function, used at bottom
- All variables initialized together, far from first use
- Large gap between variable declaration and use
- Must scroll to see variable declaration and usage together
- Variables have function/class scope when could be more local
- Can't see all uses of variable on one screen
Key Concepts
Scope
How widely visible a variable is:
- Block scope - visible only within
{}or indented block (smallest) - Loop scope - visible only within loop
- Function scope - visible throughout function
- Class scope - visible to all methods in class
- Module scope - visible throughout file
- Global scope - visible everywhere (largest, avoid)
Rule: Start with smallest scope. Expand only if necessary.
Span
Distance between successive references to a variable:
a = 0 # First reference
b = 0 # 1 line between references to a
c = 0 # 2 lines between references to a
a = b + c # Second reference
# Span of a: 2 lines
Goal: Minimize span. Keep references close together.
Live Time
Total statements between first and last reference:
recordIndex = 0 # Line 2 - first reference
# ... 24 lines of other code ...
recordIndex += 1 # Line 28 - last reference
# Live time: 28 - 2 + 1 = 27 statements
Goal: Minimize live time. Reduce window of vulnerability.
The Principle of Proximity
Keep related actions together:
❌ Bad (declarations far from use):
def process_data():
# All declarations at top
index = 0
total = 0
done = False
result = []
# 20 lines later...
while index < count:
index += 1
# 30 lines later...
while not done:
if total > threshold:
done = True
# 40 lines later...
result.append(final_value)
return result
Live times: index=25, total=35, done=35, result=40. Average: 34 lines.
✅ Good (declare close to use):
def process_data():
# Declare index right before loop that uses it
index = 0
while index < count:
index += 1
# Declare total and done right before loop that uses them
total = 0
done = False
while not done:
if total > threshold:
done = True
# Declare result right before use
result = []
result.append(final_value)
return result
Live times: index=3, total=5, done=5, result=2. Average: 4 lines.
Improvement: 34 → 4 average live time (8.5x better)
Aggressive Scope Minimization
Technique 1: Declare at Point of First Use
Languages like C++, Java, Python, JavaScript allow this:
❌ Bad:
def calculate_report():
total = 0 # Declared at top
count = 0
average = 0.0
# 10 lines later...
total = sum(values)
count = len(values)
average = total / count if count > 0 else 0.0
✅ Good:
def calculate_report():
# 10 lines of other work...
# Declare right before use
total = sum(values)
count = len(values)
average = total / count if count > 0 else 0.0
Technique 2: Use Block Scope
In languages supporting block scope, use it:
# Process old data - variables scoped to this block
{
old_data = get_old_data()
old_total = sum(old_data)
print_summary(old_data, old_total)
} # old_data, old_total die here
# Process new data - fresh variables, no collision
{
new_data = get_new_data()
new_total = sum(new_data)
print_summary(new_data, new_total)
} # new_data, new_total die here
Technique 3: Initialize at Declaration
❌ Bad:
# Declare and initialize separately
user_count: int
user_count = 0
active_users: list
active_users = []
✅ Good:
# Initialize when declaring
user_count = 0
active_users = []
Technique 4: Use Loop-Scoped Variables
Many languages support declaring loop variables in the loop:
# Variable i exists ONLY within this loop
for i in range(count):
process(i)
# i doesn't exist here
# Another loop can use i without conflict
for i in range(other_count):
process_other(i)
Technique 5: Group Related Statements
Keep statements working with same variables together:
❌ Bad (scattered):
old_
Установить Localizing Variables в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Localizing Variables?
Declare variables in smallest possible scope, initialize close to first use, minimize span and live time
Как установить скилл Localizing Variables?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Localizing Variables запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic