Improve variable and function naming with semantic analysis
I'll analyze your code and suggest better, more semantic names for variables, functions, and classes.
Arguments: $ARGUMENTS - specific files or naming focus (e.g., "functions", "variables", "types")
Code Understanding
Naming Problems to Fix
Language Conventions
Semantic Naming Principles
MANDATORY FIRST STEPS:
Let me analyze naming in your code:
# Detect programming language
echo "=== Code Analysis ==="
# Find common poorly named identifiers
echo "Checking for generic/unclear names..."
# Look for single-letter variables (excluding loop counters)
# Look for generic names like data, temp, obj, result, item
# Look for unclear abbreviations
# Analyze file types
FILE_COUNT=$(find . -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" -o -name "*.py" -o -name "*.go" -o -name "*.rs" \) 2>/dev/null | wc -l)
echo "Source files to analyze: $FILE_COUNT"
# Detect primary language
if [ -f "package.json" ]; then
if grep -q "\"typescript\"" package.json; then
echo "Primary language: TypeScript"
else
echo "Primary language: JavaScript"
fi
elif [ -f "requirements.txt" ] || [ -f "setup.py" ]; then
echo "Primary language: Python"
elif [ -f "go.mod" ]; then
echo "Primary language: Go"
elif [ -f "Cargo.toml" ]; then
echo "Primary language: Rust"
fi
I'll identify common naming anti-patterns:
Generic Names:
data, info, obj, item, element, thingresult, output, temp, tmplist, array, collection (without context)manager, handler, helper, util (vague suffixes)Single Letter Names:
x, y, z (outside math/coordinates)a, b, c (meaningless)i, j, k (beyond simple loop counters)e (for error - should be error)Unclear Abbreviations:
usr โ usercfg โ configmsg โ messagebtn โ buttonarr โ array (or better, describe contents)num โ number or specific quantityMisleading Names:
getData() that modifies state โ fetchAndStoreData()isValid() with side effects โ validateAndLog()process() โ be specific about what's processedInconsistent Patterns:
getUser() and fetchProfile()userId and user_idisEnabled and hasAccessUsing native tools:
Based on context and usage, I'll suggest better names:
Before:
// Generic, unclear names
const data = await fetch('/api/users');
const result = data.json();
const list = result.map(item => item.name);
const temp = list.filter(x => x.length > 5);
After:
// Descriptive, intention-revealing names
const usersResponse = await fetch('/api/users');
const users = await usersResponse.json();
const userNames = users.map(user => user.name);
const longUserNames = userNames.filter(name => name.length > 5);
Before:
// Vague function names
function process(data) {
const result = data.filter(x => x.active);
return result;
}
function handle(item) {
item.status = 'done';
save(item);
}
function get() {
return state.user;
}
After:
// Specific, action-oriented names
function filterActiveUsers(users) {
return users.filter(user => user.active);
}
function markItemAsCompleteAndSave(item) {
item.status = 'done';
save(item);
}
function getCurrentUser() {
return state.user;
}
Before:
// Generic, unclear class names
class Manager {
handle(data) { }
}
class Helper {
process(item) { }
}
interface Data {
info: string;
stuff: any;
}
After:
// Specific, domain-focused names
class UserSessionManager {
authenticateUser(credentials) { }
}
class DateFormatter {
formatToISO(date) { }
}
interface UserProfile {
displayName: string;
preferences: UserPreferences;
}
I'll analyze how identifiers are used to suggest contextual names:
Usage Analysis:
// Analyze this code:
const data = await fetchFromDatabase();
const filtered = data.filter(x => x.age > 18);
const sorted = filtered.sort((a, b) => a.name.localeCompare(b.name));
const result = sorted.slice(0, 10);
Context Understanding:
data is fetched from database โ likely users, products, etc.age > 18 โ adults or eligible usersname โ alphabetically orderedImproved Version:
const allUsers = await fetchUsersFromDatabase();
const adultUsers = allUsers.filter(user => user.age > 18);
const alphabeticalUsers = adultUsers.sort((a, b) =>
a.name.localeCompare(b.name)
);
const topTenUsers = alphabeticalUsers.slice(0, 10);
// Or with descriptive pipeline:
const topTenAdultUsersSorted = await fetchUsersFromDatabase()
.then(users => users.filter(user => user.age > 18))
.then(adults => adults.sort((a, b) => a.name.localeCompare(b.name)))
.then(sorted => sorted.slice(0, 10));
I'll apply language-specific naming best practices:
Conventions:
camelCasePascalCaseUPPER_SNAKE_CASE or camelCase_prefixWithUnderscore (legacy) or #privateField (modern)is, has, should prefixesExamples:
// Variables
const userProfile = getUserProfile();
const isAuthenticated = checkAuth();
const hasPermission = user.permissions.includes('admin');
// Functions
function calculateTotalPrice(items: CartItem[]): number { }
function shouldDisplayNotification(user: User): boolean { }
// Classes
class UserAuthenticationService { }
class ProductInventoryManager { }
// Constants
const MAX_RETRY_ATTEMPTS = 3;
const API_BASE_URL = 'https://api.example.com';
// Interfaces/Types
interface UserProfile { }
type PaymentMethod = 'card' | 'paypal' | 'crypto';
Conventions:
snake_casePascalCaseUPPER_SNAKE_CASE_prefix_with_underscoreis_, has_, should_ prefixesExamples:
# Variables
user_profile = get_user_profile()
is_authenticated = check_auth()
has_permission = 'admin' in user.permissions
# Functions
def calculate_total_price(items: list[CartItem]) -> float:
pass
def should_display_notification(user: User) -> bool:
pass
# Classes
class UserAuthenticationService:
pass
class ProductInventoryManager:
pass
# Constants
MAX_RETRY_ATTEMPTS = 3
API_BASE_URL = 'https://api.example.com'
Conventions:
UserService)userService)HTTPServer, URLParser)Get prefix (user.Name() not user.GetName())Examples:
// Exported
type UserAuthenticationService struct {}
func (s *UserAuthenticationService) AuthenticateUser() {}
// Unexported
var maxRetryAttempts = 3
func calculateTotalPrice(items []CartItem) float64 {}
// Acronyms
type HTTPClient struct {}
type URLParser struct {}
// Getters (no Get prefix)
func (u *User) Name() string { return u.name }
I'll safely rename identifiers across the codebase:
Renaming Strategy:
Safety Checks:
Example Refactoring:
// Before: Poor naming
function proc(d) {
const r = d.filter(x => x.s === 'a');
const t = r.length;
return t > 0;
}
// After: Clear naming
function hasActiveUsers(users) {
const activeUsers = users.filter(user => user.status === 'active');
const activeUserCount = activeUsers.length;
return activeUserCount > 0;
}
// Or even better (more concise):
function hasActiveUsers(users) {
return users.some(user => user.status === 'active');
}
Expected range: 1,200โ2,000 tokens (initial), 300 tokens (cache hit)
Caching: Caches naming conventions in .claude/cache/naming_conventions.json for 7 days. Invalidated when tsconfig.json changes.
Early exit: Returns immediately after critical-severity issues so they are addressed first.
Patterns used: Grep-before-Read, early exit, progressive disclosure, caching