detect-code-smells

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Detect Code Smells

检测Code Smell

Detect common code smells and anti-patterns in code, providing immediate feedback on quality issues.
检测代码中的常见Code Smell与反模式,针对质量问题提供即时反馈。

Code Smell Categories

Code Smell分类

1. Complexity Smells

1. 复杂度类异味

  • Long Method: Functions/methods > 50 lines
  • Long Parameter List: > 4 parameters
  • Complex Conditionals: Deeply nested if/else, complex boolean expressions
  • High Cyclomatic Complexity: > 10 branches
  • Deep Nesting: > 4 levels of indentation
  • Long Method: 函数/方法超过50行
  • Long Parameter List: 参数数量超过4个
  • Complex Conditionals: 深层嵌套的if/else、复杂布尔表达式
  • High Cyclomatic Complexity: 分支数量超过10个
  • Deep Nesting: 缩进层级超过4层

2. Duplication Smells

2. 重复类异味

  • Duplicate Code: Repeated code blocks
  • Similar Functions: Functions with nearly identical logic
  • Magic Numbers: Hardcoded numbers without explanation
  • String Duplication: Repeated string literals
  • Duplicate Code: 重复的代码块
  • Similar Functions: 逻辑几乎完全相同的函数
  • Magic Numbers: 未加说明的硬编码数字
  • String Duplication: 重复的字符串字面量

3. Naming Smells

3. 命名类异味

  • Unclear Names: Single letter variables (except loop counters)
  • Hungarian Notation: Unnecessary type prefixes
  • Inconsistent Naming: Mixed camelCase/snake_case
  • Abbreviated Names: Unclear abbreviations (mgr, ctx, tmp)
  • Misleading Names: Name doesn't match behavior
  • Unclear Names: 单字母变量(循环计数器除外)
  • Hungarian Notation: 不必要的类型前缀
  • Inconsistent Naming: 混合使用camelCase与snake_case命名风格
  • Abbreviated Names: 含义模糊的缩写(如mgr、ctx、tmp)
  • Misleading Names: 名称与实际行为不符

4. Object-Oriented Smells

4. 面向对象类异味

  • God Class: Class > 500 lines or too many responsibilities
  • Data Class: Class with only getters/setters
  • Feature Envy: Method uses more of another class than its own
  • Inappropriate Intimacy: Classes too dependent on internal details
  • Lazy Class: Class doing too little to justify existence
  • God Class: 代码量超过500行或承担过多职责的类
  • Data Class: 仅包含getter/setter方法的类
  • Feature Envy: 方法对其他类的依赖远超过自身类
  • Inappropriate Intimacy: 类之间过度依赖内部实现细节
  • Lazy Class: 职责过少、没有存在必要的类

5. Functional Smells

5. 函数式类异味

  • Side Effects: Function modifies external state unexpectedly
  • Non-Pure Functions: Functions with hidden dependencies
  • Mutability Issues: Unexpected mutation of objects
  • Callback Hell: Deeply nested callbacks
  • Side Effects: 意外修改外部状态的函数
  • Non-Pure Functions: 存在隐藏依赖的函数
  • Mutability Issues: 对象被意外修改的问题
  • Callback Hell: 深层嵌套的回调函数

6. Architecture Smells

6. 架构类异味

  • Circular Dependencies: Module A depends on B, B depends on A
  • Missing Abstraction: Concrete implementations without interfaces
  • Tight Coupling: Hard dependencies on specific implementations
  • Leaky Abstraction: Implementation details exposed through interface
  • Circular Dependencies: 模块A依赖模块B,同时模块B依赖模块A
  • Missing Abstraction: 只有具体实现、缺少接口的情况
  • Tight Coupling: 对特定实现存在强依赖
  • Leaky Abstraction: 接口暴露了底层实现细节

Detection Process

检测流程

  1. Parse file - Analyze syntax tree and structure
  2. Identify patterns - Look for known code smell patterns
  3. Calculate metrics - Measure complexity, length, duplication
  4. Assess severity - Determine impact of each smell
  5. Generate report - Provide actionable feedback
  1. 解析文件 - 分析语法树与结构
  2. 识别模式 - 查找已知的Code Smell模式
  3. 计算指标 - 测量复杂度、长度、重复率
  4. 评估严重程度 - 确定每个异味的影响程度
  5. 生成报告 - 提供可执行的改进建议

Analysis Techniques

分析技术

  • Abstract Syntax Tree (AST) parsing
  • Pattern matching against known smells
  • Metric calculation (LOC, complexity, coupling)
  • Comparison with language-specific best practices
  • Context-aware analysis (test files have different standards)
  • 抽象语法树(AST)解析
  • 与已知异味模式进行匹配
  • 指标计算(代码行数LOC、复杂度、耦合度)
  • 与特定语言的最佳实践进行对比
  • 上下文感知分析(测试文件采用不同标准)

Return Value

返回值

Return object:
json
{
  "file": "path/to/file.js",
  "language": "javascript",
  "overallScore": 7.5,
  "smells": [
    {
      "type": "Long Method",
      "severity": "warning",
      "location": {
        "line": 42,
        "endLine": 95,
        "function": "processUserData"
      },
      "description": "Function 'processUserData' is 53 lines long",
      "suggestion": "Extract smaller functions for validation, transformation, and persistence",
      "impact": "Harder to understand, test, and maintain",
      "effort": "medium"
    },
    {
      "type": "Complex Conditional",
      "severity": "warning",
      "location": {
        "line": 67,
        "column": 8
      },
      "description": "Nested conditional with 5 levels of nesting",
      "suggestion": "Extract conditions into well-named boolean variables or separate functions",
      "impact": "Difficult to understand logic flow",
      "effort": "small"
    }
  ],
  "metrics": {
    "linesOfCode": 234,
    "averageComplexity": 4.2,
    "maxComplexity": 12,
    "duplicationPercentage": 8.5
  },
  "recommendations": [
    "Extract 'processUserData' into smaller single-purpose functions",
    "Replace complex conditional at line 67 with early returns",
    "Consider extracting repeated validation logic into a helper function"
  ]
}
返回对象:
json
{
  "file": "path/to/file.js",
  "language": "javascript",
  "overallScore": 7.5,
  "smells": [
    {
      "type": "Long Method",
      "severity": "warning",
      "location": {
        "line": 42,
        "endLine": 95,
        "function": "processUserData"
      },
      "description": "Function 'processUserData' is 53 lines long",
      "suggestion": "Extract smaller functions for validation, transformation, and persistence",
      "impact": "Harder to understand, test, and maintain",
      "effort": "medium"
    },
    {
      "type": "Complex Conditional",
      "severity": "warning",
      "location": {
        "line": 67,
        "column": 8
      },
      "description": "Nested conditional with 5 levels of nesting",
      "suggestion": "Extract conditions into well-named boolean variables or separate functions",
      "impact": "Difficult to understand logic flow",
      "effort": "small"
    }
  ],
  "metrics": {
    "linesOfCode": 234,
    "averageComplexity": 4.2,
    "maxComplexity": 12,
    "duplicationPercentage": 8.5
  },
  "recommendations": [
    "Extract 'processUserData' into smaller single-purpose functions",
    "Replace complex conditional at line 67 with early returns",
    "Consider extracting repeated validation logic into a helper function"
  ]
}

Examples

示例

Example 1: Detecting Long Method

示例1:检测Long Method

Context: User opens
user-service.js
containing a 150-line function
Autonomous Invocation: Skill automatically analyzes the file and reports:
Code Smell Detected: Long Method

Function 'handleUserRegistration' (lines 23-172) is 150 lines long.

Impact: This function is doing too many things, making it:
- Hard to understand at a glance
- Difficult to test thoroughly
- Prone to bugs when modified
- Challenging to reuse parts of its logic

Suggestion: Extract into smaller functions:
- validateRegistrationData() - lines 23-45
- checkEmailAvailability() - lines 46-68
- createUserAccount() - lines 69-98
- sendWelcomeEmail() - lines 99-130
- logRegistrationEvent() - lines 131-172

This follows the Single Responsibility Principle and makes each piece independently testable.
场景:用户打开包含150行函数的
user-service.js
文件
自动触发:该技能自动分析文件并生成报告:
Code Smell Detected: Long Method

Function 'handleUserRegistration' (lines 23-172) is 150 lines long.

Impact: This function is doing too many things, making it:
- Hard to understand at a glance
- Difficult to test thoroughly
- Prone to bugs when modified
- Challenging to reuse parts of its logic

Suggestion: Extract into smaller functions:
- validateRegistrationData() - lines 23-45
- checkEmailAvailability() - lines 46-68
- createUserAccount() - lines 69-98
- sendWelcomeEmail() - lines 99-130
- logRegistrationEvent() - lines 131-172

This follows the Single Responsibility Principle and makes each piece independently testable.

Example 2: Detecting Complex Conditional

示例2:检测Complex Conditional

Context: User working on file with deeply nested if/else
Autonomous Invocation: Skill detects and suggests:
Code Smell Detected: Complex Conditional

Lines 45-72 contain a deeply nested conditional (5 levels deep) with multiple boolean conditions.

Current pattern:
if (user) {
  if (user.isActive) {
    if (user.hasPermission('admin')) {
      if (validateToken(user.token)) {
        // ... more nesting
      }
    }
  }
}

Refactoring suggestion using guard clauses:
if (!user) return null;
if (!user.isActive) return null;
if (!user.hasPermission('admin')) return null;
if (!validateToken(user.token)) return null;

// Now do the work without nesting

Benefits: Reduces cognitive load, clearer failure conditions, easier to test edge cases.
场景:用户正在处理包含深层嵌套if/else的文件
自动触发:该技能检测到问题并给出建议:
Code Smell Detected: Complex Conditional

Lines 45-72 contain a deeply nested conditional (5 levels deep) with multiple boolean conditions.

Current pattern:
if (user) {
  if (user.isActive) {
    if (user.hasPermission('admin')) {
      if (validateToken(user.token)) {
        // ... more nesting
      }
    }
  }
}

Refactoring suggestion using guard clauses:
if (!user) return null;
if (!user.isActive) return null;
if (!user.hasPermission('admin')) return null;
if (!validateToken(user.token)) return null;

// Now do the work without nesting

Benefits: Reduces cognitive load, clearer failure conditions, easier to test edge cases.

Example 3: Detecting Code Duplication

示例3:检测代码重复

Context: User reviewing file with repeated code blocks
Autonomous Invocation: Skill identifies DRY violation:
Code Smell Detected: Duplicate Code

Found 3 nearly identical code blocks:
- Lines 34-42 (in fetchUserById)
- Lines 78-86 (in fetchUserByEmail)
- Lines 112-120 (in fetchUserByUsername)

All three blocks implement the same error handling and response formatting logic.

Suggestion: Extract common logic into a helper function:

function handleUserFetchResponse(result, errorMessage) {
  if (!result) {
    throw new Error(errorMessage);
  }
  return formatUserResponse(result);
}

Then simplify each call site:
const user = await db.query(...);
return handleUserFetchResponse(user, 'User not found');

Impact: Reduces maintenance burden, ensures consistent behavior, fewer bugs.
场景:用户正在评审包含重复代码块的文件
自动触发:该技能识别出违反DRY原则的问题:
Code Smell Detected: Duplicate Code

Found 3 nearly identical code blocks:
- Lines 34-42 (in fetchUserById)
- Lines 78-86 (in fetchUserByEmail)
- Lines 112-120 (in fetchUserByUsername)

All three blocks implement the same error handling and response formatting logic.

Suggestion: Extract common logic into a helper function:

function handleUserFetchResponse(result, errorMessage) {
  if (!result) {
    throw new Error(errorMessage);
  }
  return formatUserResponse(result);
}

Then simplify each call site:
const user = await db.query(...);
return handleUserFetchResponse(user, 'User not found');

Impact: Reduces maintenance burden, ensures consistent behavior, fewer bugs.

Error Handling

错误处理

  • If file cannot be parsed: Return error with details about syntax issue
  • If language not supported: Suggest manual review or generic analysis
  • If file is too large (> 10k lines): Warn about God Object and suggest splitting
  • If file is test file: Apply different standards (longer functions acceptable)
  • If file is generated: Skip analysis or warn user
  • 若文件无法解析:返回包含语法问题详情的错误信息
  • 若语言不被支持:建议手动评审或通用分析
  • 若文件过大(超过10000行):警告可能存在上帝对象(God Object)并建议拆分文件
  • 若文件为测试文件:应用不同标准(允许更长的函数)
  • 若文件为自动生成:跳过分析或向用户发出警告

Context Awareness

上下文感知

Test Files

测试文件

  • Allow longer functions (tests often have setup/teardown)
  • Allow more duplication (explicit tests > DRY)
  • Different naming conventions acceptable
  • 允许更长的函数(测试通常包含初始化/清理逻辑)
  • 允许更多重复代码(显式测试优先于DRY原则)
  • 接受不同的命名规范

Configuration Files

配置文件

  • JSON/YAML: Check for structural issues
  • Don't apply code smell rules meant for logic
  • JSON/YAML:检查结构问题
  • 不应用针对业务逻辑的Code Smell规则

Legacy Code

遗留代码

  • Flag issues but acknowledge inherited constraints
  • Prioritize critical issues over stylistic ones
  • Suggest incremental improvement approach
  • 标记问题但承认历史约束
  • 优先处理严重问题而非风格问题
  • 建议采用增量改进方式

Generated Code

自动生成的代码

  • Identify if file is auto-generated
  • Suggest improving generator rather than generated code
  • Skip some smell checks
  • 识别文件是否为自动生成
  • 建议改进生成器而非修改生成的代码
  • 跳过部分异味检查

Integration with Development Workflow

与开发工作流的集成

  • Non-intrusive: Provides info but doesn't block work
  • Actionable: Specific suggestions with examples
  • Educational: Explains why something is a smell
  • Prioritized: Critical issues highlighted over minor ones
  • Context-sensitive: Understands different file types
  • 非侵入式:提供信息但不阻碍工作
  • 可执行:附带示例的具体建议
  • 教育性:解释问题为何属于Code Smell
  • 优先级明确:突出严重问题而非次要问题
  • 上下文敏感:理解不同类型文件的差异

Related Skills

相关技能

  • suggest-performance-fix
    : Focuses on performance issues
  • security-pattern-check
    : Focuses on security concerns
  • suggest-performance-fix
    : 专注于性能问题
  • security-pattern-check
    : 专注于安全问题

Notes

说明

This skill acts as a senior developer looking over your shoulder, catching issues that might be missed during fast-paced development. It doesn't replace human code review but augments it by catching obvious issues early.
该技能如同资深开发人员在旁把关,能够捕捉快节奏开发中可能被忽略的问题。它无法替代人工代码评审,但可以提前发现明显问题,作为人工评审的补充。