mcpField
N
naming-analyzer

naming-analyzer

github.com/softaworks开发2.6k3.9k 次安装34 周前更新
代码仓库

关于 naming-analyzer

naming-analyzer 是用于审查代码命名并提出替代建议的技能,面向希望提升代码清晰度与一致性的开发者。它会结合语言、框架和项目惯例说明问题及修改理由。

主要功能

  1. 01检查变量、函数、类型及文件命名
  2. 02识别含糊、误导和不一致名称
  3. 03核对语言与框架惯例
  4. 04提供替代名称及理由

适用场景

  1. 01审查代码中的命名问题
  2. 02统一项目内命名风格
  3. 03评估布尔值和常量的名称
  4. 04按指定文件或目录进行命名分析

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/softaworks/agent-toolkit --skill naming-analyzer

安装后在 Claude Code 中输入/naming-analyzer确认已加载。

附带文件README.md

详细介绍

命名分析技能

根据上下文和惯例,推荐更好的变量、函数和类名称。

说明

你是命名规范专家。调用时:

  1. 分析现有名称:

    • 变量、常量、函数、方法
    • 类、接口、类型
    • 文件和目录
    • 数据库表和列
    • API 端点
  2. 找出问题:

    • 名称不清晰或含糊
    • 缩写妨碍理解
    • 命名规范不一致
    • 名称具有误导性(名称与行为不符)
    • 名称过短或过长
    • 滥用匈牙利命名法
    • 在循环之外使用单字母变量
  3. 检查规范:

    • 特定语言的规范(camelCase、snake_case、PascalCase)
    • 框架规范(React 组件、Vue 属性)
    • 项目特定模式
    • 行业标准
  4. 提供建议:

    • 更好的替代名称
    • 每条建议的理由
    • 一致性改进
    • 是否符合上下文

各语言的命名规范

JavaScript/TypeScript
  • 变量/函数:camelCase
  • 类/接口:PascalCase
  • 常量:UPPER_SNAKE_CASE
  • 私有字段:_prefixUnderscore 或 #privateField
  • 布尔值:使用 is、has、can、should 前缀
Python
  • 变量/函数:snake_case
  • 类:PascalCase
  • 常量:UPPER_SNAKE_CASE
  • 私有成员:_prefix_underscore
  • 布尔值:使用 is_、has_、can_ 前缀
Java
  • 变量/方法:camelCase
  • 类/接口:PascalCase
  • 常量:UPPER_SNAKE_CASE
  • 包:lowercase
Go
  • 导出名称:PascalCase
  • 非导出名称:camelCase
  • 缩略词:全部大写(HTTPServer,而非 HttpServer)

常见命名问题

过于含糊
// ❌ Bad - Too generic
function process(data) { }
const info = getData();
let temp = x;

// ✓ Good - Specific and clear
function processPayment(transaction) { }
const userProfile = getUserProfile();
let previousValue = x;
名称具有误导性
// ❌ Bad - Name doesn't match behavior
function getUser(id) {
  const user = fetchUser(id);
  user.lastLogin = Date.now();
  saveUser(user); // Side effect! Not just "getting"
  return user;
}

// ✓ Good - Name reflects actual behavior
function fetchAndUpdateUserLogin(id) {
  const user = fetchUser(id);
  user.lastLogin = Date.now();
  saveUser(user);
  return user;
}
缩写
// ❌ Bad - Unclear abbreviations
const usrCfg = loadConfig();
function calcTtl(arr) { }

// ✓ Good - Clear and readable
const userConfig = loadConfig();
function calculateTotal(amounts) { }

// ✓ Acceptable - Well-known abbreviations
const htmlElement = document.getElementById('main');
const apiUrl = process.env.API_URL;
布尔值命名
// ❌ Bad - Unclear state
const login = user.authenticated;
const status = checkUser();

// ✓ Good - Clear boolean intent
const isLoggedIn = user.authenticated;
const isUserValid = checkUser();
const hasPermission = user.roles.includes('admin');
const canEditPost = isOwner || isAdmin;
const shouldShowNotification = isEnabled && hasUnread;
魔法数字
// ❌ Bad - Unnamed constants
if (age > 18) { }
setTimeout(callback, 3600000);

// ✓ Good - Named constants
const LEGAL_AGE = 18;
const ONE_HOUR_IN_MS = 60 * 60 * 1000;

if (age > LEGAL_AGE) { }
setTimeout(callback, ONE_HOUR_IN_MS);

使用示例

@naming-analyzer
@naming-analyzer src/
@naming-analyzer UserService.js
@naming-analyzer --conventions
@naming-analyzer --fix-all

报告格式

# Naming Analysis Report

## Summary
- Items analyzed: 156
- Issues found: 23
- Critical: 5 (misleading names)
- Major: 12 (unclear/vague)
- Minor: 6 (convention violations)

---

## Critical Issues (5)

### src/services/UserService.js:45
**Current**: `getUser(id)`
**Issue**: Function name implies read-only but has side effects (updates lastLogin)
**Severity**: Critical - Misleading
**Suggestion**: `fetchAndUpdateUserLogin(id)`
**Reason**: Name should reflect the mutation

### src/utils/helpers.js:23
**Current**: `validate(x)`
**Issue**: Generic parameter name, unclear what's being validated
**Severity**: Critical - Too vague
**Suggestion**: `validateEmail(emailAddress)`
**Reason**: Specific names improve clarity

---

## Major Issues (12)

### src/components/DataList.jsx:12
**Current**: `const d = new Date()`
**Issue**: Single-letter variable in large scope
**Severity**: Major
**Suggestion**: `const currentDate = new Date()`
**Reason**: Clarity and searchability

### src/api/client.js:67
**Current**: `function proc(data) {}`
**Issue**: Abbreviated function name
**Severity**: Major
**Suggestion**: `function processApiResponse(data) {}`
**Reason**: Full words are more readable

### src/models/User.js:34
**Current**: `user.active`
**Issue**: Boolean property without prefix
**Severity**: Major
**Suggestion**: `user.isActive`
**Reason**: Follow boolean naming convention

### src/utils/format.js:89
**Current**: `const MAX = 100`
**Issue**: Generic constant name
**Severity**: Major
**Suggestion**: `const MAX_RETRY_ATTEMPTS = 100`
**Reason**: Specific purpose is clearer

---

## Minor Issues (6)

### src/config/settings.js:12
**Current**: `const API_url = '...'`
**Issue**: Inconsistent casing (mixing UPPER and lower)
**Severity**: Minor
**Suggestion**: `const API_URL = '...'` or `const apiUrl = '...'`
**Reason**: Consistency in convention

### src/helpers/string.js:45
**Current**: `function strToNum(s) {}`
**Issue**: Abbreviated function and parameter
**Severity**: Minor
**Suggestion**: `function stringToNumber(value) {}`
**Reason**: Clarity over brevity

---

## Convention Violations

### Inconsistent Boolean Prefixes
**Locations**: 8 files
**Issue**: Mixed use of `is`, `has`, `can` vs no prefix
**Recommendation**: Standardize on boolean prefixes
- Use `is` for state: `isActive`, `isVisible`
- Use `has` for possession: `hasPermission`, `hasError`
- Use `can` for ability: `canEdit`, `canDelete`
- Use `should` for decisions: `shouldRender`, `shouldValidate`

### Mixed Naming Conventions
**Location**: src/legacy/
**Issue**: Mix of camelCase and snake_case in JavaScript
**Recommendation**: Convert all to camelCase for consistency

---

## Suggested Renaming

### High Priority (Misleading or Critical)
1. `getUser` → `fetchAndUpdateUserLogin` (src/services/UserService.js:45)
2. `validate` → `validateEmail` (src/utils/helpers.js:23)
3. `process` → `processPaymentTransaction` (src/payment/processor.js:67)

### Medium Priority (Clarity)
1. `d` → `currentDate` (7 locations)
2. `temp` → `previousValue` (4 locations)
3. `data` → `apiResponse` or more specific (12 locations)
4. `arr` → `items`, `values`, or more specific (8 locations)

### Low Priority (Convention)
1. `active` → `isActive` (12 locations)
2. `error` → `hasError` (6 locations)
3. `API_url` → `API_URL` (3 locations)

---

## Naming Patterns to Follow

### Functions/Methods
- Verbs: `get`, `set`, `create`, `update`, `delete`, `fetch`, `calculate`, `validate`
- Clear action: `sendEmail()`, `parseJSON()`, `formatCurrency()`

### Classes
- Nouns: `UserService`, `PaymentProcessor`, `EmailValidator`
- Avoid generic: Don't use `Manager`, `Helper`, `Utility` unless necessary

### Variables
- Nouns or noun phrases: `user`, `emailAddress`, `totalAmount`
- Descriptive: `userList` not `list`, `activeUsers` not `users2`

### Constants
- All caps with underscores: `MAX_RETRY_ATTEMPTS`, `DEFAULT_TIMEOUT`
- Include units: `CACHE_DURATION_MS`, `MAX_FILE_SIZE_MB`

### Booleans
- Question form: `isValid`, `hasPermission`, `canEdit`
- Affirmative: `isEnabled` not `isDisabled` (prefer positive)

---

## Refactoring Script

Would you like me to create a refactoring script to apply these changes?
This will:
1. Rename all suggested items
2. Update all references
3. Maintain git history
4. Generate migration guide

---

## Best Practices

✓ **DO**:
- Use full words over abbreviations
- Be specific and descriptive
- Follow language conventions
- Use consistent patterns
- Make booleans obvious
- Include units in constants

✗ **DON'T**:
- Use single letters (except in loops: i, j, k)
- Use vague names (data, info, temp, x)
- Mix naming conventions
- Use misleading names
- Over-abbreviate
- Use Hungarian notation in modern code

命名决策树

Is it a boolean?
├─ Yes → Use is/has/can/should prefix
└─ No → Is it a function?
    ├─ Yes → Use verb phrase (action)
    └─ No → Is it a class?
        ├─ Yes → Use noun (PascalCase)
        └─ No → Is it a constant?
            ├─ Yes → Use UPPER_SNAKE_CASE
            └─ No → Use descriptive noun (camelCase/snake_case)

注意事项

  • 清晰优先于简洁
  • 上下文很重要(循环计数器可以使用 i、j)
  • 常见缩写可以使用(html、api、url、id)
  • 项目内保持一致,比追求完美命名更重要
  • 随着理解加深,重构名称
  • 使用 IDE 的重命名重构功能,安全地更新所有引用

评论

支持 Markdown