code-antipatterns-analysis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Anti-patterns Analysis

代码反模式分析

Expert knowledge for systematic detection and analysis of anti-patterns, code smells, and quality issues across codebases using ast-grep and parallel agent delegation.
本技能提供使用ast-grep和并行Agent委托对代码库中的反模式、代码异味和质量问题进行系统性检测与分析的专业知识。

Analysis Philosophy

分析理念

This skill emphasizes parallel delegation for comprehensive analysis. Rather than sequentially scanning for issues, launch multiple specialized agents to examine different categories simultaneously, then consolidate findings.
本技能强调采用并行委托实现全面分析。不同于按顺序扫描问题,我们会启动多个专业Agent同时检查不同类别问题,然后整合分析结果。

Analysis Categories

分析类别

1. JavaScript/TypeScript Anti-patterns

1. JavaScript/TypeScript 反模式

Callback Hell & Async Issues
bash
undefined
回调地狱与异步问题
bash
undefined

Nested callbacks (3+ levels)

Nested callbacks (3+ levels)

ast-grep -p '$FUNC($$$, function($$$) { $FUNC2($$$, function($$$) { $$$ }) })' --lang js
ast-grep -p '$FUNC($$$, function($$$) { $FUNC2($$$, function($$$) { $$$ }) })' --lang js

Missing error handling in async

Missing error handling in async

ast-grep -p 'async function $NAME($$$) { $$$ }' --lang js
ast-grep -p 'async function $NAME($$$) { $$$ }' --lang js

Then check if try-catch is present

Then check if try-catch is present

Unhandled promise rejection

Unhandled promise rejection

ast-grep -p '$PROMISE.then($$$)' --lang js
ast-grep -p '$PROMISE.then($$$)' --lang js

Without .catch() - use composite rule

Without .catch() - use composite rule


**Magic Values**
```bash

**魔法值**
```bash

Magic numbers in comparisons

Magic numbers in comparisons

ast-grep -p 'if ($VAR > 100)' --lang js ast-grep -p 'if ($VAR < 50)' --lang js ast-grep -p 'if ($VAR === 42)' --lang js
ast-grep -p 'if ($VAR > 100)' --lang js ast-grep -p 'if ($VAR < 50)' --lang js ast-grep -p 'if ($VAR === 42)' --lang js

Magic strings

Magic strings

ast-grep -p "if ($VAR === 'admin')" --lang js

**Empty Catch Blocks**
```bash
ast-grep -p 'try { $$$ } catch ($E) { }' --lang js
Console Statements (Debug Leftovers)
bash
ast-grep -p 'console.log($$$)' --lang js
ast-grep -p 'console.debug($$$)' --lang js
ast-grep -p 'console.warn($$$)' --lang js
Use let/const for Variable Declarations
bash
ast-grep -p 'var $VAR = $$$' --lang js
ast-grep -p "if ($VAR === 'admin')" --lang js

**空Catch块**
```bash
ast-grep -p 'try { $$$ } catch ($E) { }' --lang js
控制台语句(调试遗留代码)
bash
ast-grep -p 'console.log($$$)' --lang js
ast-grep -p 'console.debug($$$)' --lang js
ast-grep -p 'console.warn($$$)' --lang js
使用let/const声明变量
bash
ast-grep -p 'var $VAR = $$$' --lang js

2. Vue 3 Anti-patterns

2. Vue 3 反模式

Props Mutation
yaml
undefined
Props 直接修改
yaml
undefined

YAML rule for props mutation detection

YAML rule for props mutation detection

id: vue-props-mutation language: JavaScript message: Use computed properties or emit events to update props rule: pattern: props.$PROP = $VALUE

```bash
id: vue-props-mutation language: JavaScript message: Use computed properties or emit events to update props rule: pattern: props.$PROP = $VALUE

```bash

Direct prop assignment

Direct prop assignment

ast-grep -p 'props.$PROP = $VALUE' --lang js

**Missing Keys in v-for**
```bash
ast-grep -p 'props.$PROP = $VALUE' --lang js

**v-for 缺失Key**
```bash

Search in Vue templates

Search in Vue templates

ast-grep -p 'v-for="$ITEM in $LIST"' --lang html
ast-grep -p 'v-for="$ITEM in $LIST"' --lang html

Check if :key is present nearby

Check if :key is present nearby


**Options API in Composition API Codebase**
```bash

**组合式API代码库中使用选项式API**
```bash

Find Options API usage

Find Options API usage

ast-grep -p 'export default { data() { $$$ } }' --lang js ast-grep -p 'export default { methods: { $$$ } }' --lang js ast-grep -p 'export default { computed: { $$$ } }' --lang js
ast-grep -p 'export default { data() { $$$ } }' --lang js ast-grep -p 'export default { methods: { $$$ } }' --lang js ast-grep -p 'export default { computed: { $$$ } }' --lang js

vs Composition API

vs Composition API

ast-grep -p 'defineComponent({ setup($$$) { $$$ } })' --lang js

**Reactive State Issues**
```bash
ast-grep -p 'defineComponent({ setup($$$) { $$$ } })' --lang js

**响应式状态问题**
```bash

Destructuring reactive state (loses reactivity)

Destructuring reactive state (loses reactivity)

ast-grep -p 'const { $$$PROPS } = $REACTIVE' --lang js
ast-grep -p 'const { $$$PROPS } = $REACTIVE' --lang js

Should use toRefs

Should use toRefs

ast-grep -p 'const { $$$PROPS } = toRefs($REACTIVE)' --lang js
undefined
ast-grep -p 'const { $$$PROPS } = toRefs($REACTIVE)' --lang js
undefined

3. TypeScript Quality Issues

3. TypeScript 质量问题

Excessive
any
Usage
bash
ast-grep -p ': any' --lang ts
ast-grep -p 'as any' --lang ts
ast-grep -p '<any>' --lang ts
Non-null Assertions
bash
ast-grep -p '$VAR!' --lang ts
ast-grep -p '$VAR!.$PROP' --lang ts
Type Assertions Instead of Guards
bash
ast-grep -p '$VAR as $TYPE' --lang ts
Missing Return Types
bash
undefined
过度使用
any
类型
bash
ast-grep -p ': any' --lang ts
ast-grep -p 'as any' --lang ts
ast-grep -p '<any>' --lang ts
非空断言
bash
ast-grep -p '$VAR!' --lang ts
ast-grep -p '$VAR!.$PROP' --lang ts
使用类型断言而非类型守卫
bash
ast-grep -p '$VAR as $TYPE' --lang ts
缺失返回类型
bash
undefined

Functions without return type annotations

Functions without return type annotations

ast-grep -p 'function $NAME($$$) { $$$ }' --lang ts
ast-grep -p 'function $NAME($$$) { $$$ }' --lang ts

Check if return type is present

Check if return type is present

undefined
undefined

4. Async/Promise Patterns

4. Async/Promise 模式

Unhandled Promises
bash
undefined
未处理的Promise
bash
undefined

Promise without await or .then/.catch

Promise without await or .then/.catch

ast-grep -p '$ASYNC_FUNC($$$)' --lang js
ast-grep -p '$ASYNC_FUNC($$$)' --lang js

Context: check if result is used

Context: check if result is used

Floating promises (no await)

Floating promises (no await)

ast-grep -p '$PROMISE_RETURNING()' --lang ts

**Nested Callbacks (Pyramid of Doom)**
```bash
ast-grep -p '$F1($$$, function($$$) { $F2($$$, function($$$) { $F3($$$, function($$$) { $$$ }) }) })' --lang js
Promise Constructor Anti-pattern
bash
undefined
ast-grep -p '$PROMISE_RETURNING()' --lang ts

**嵌套回调(厄运金字塔)**
```bash
ast-grep -p '$F1($$$, function($$$) { $F2($$$, function($$$) { $F3($$$, function($$$) { $$$ }) }) })' --lang js
Promise构造函数反模式
bash
undefined

Wrapping already-async code in new Promise

Wrapping already-async code in new Promise

ast-grep -p 'new Promise(($RESOLVE, $REJECT) => { $ASYNC_FUNC($$$).then($$$) })' --lang js
undefined
ast-grep -p 'new Promise(($RESOLVE, $REJECT) => { $ASYNC_FUNC($$$).then($$$) })' --lang js
undefined

5. Code Complexity

5. 代码复杂度

Long Functions (Manual Review)
bash
undefined
长函数(人工评审)
bash
undefined

Find function definitions, then count lines

Find function definitions, then count lines

ast-grep -p 'function $NAME($$$) { $$$ }' --lang js --json | jq '.[] | select(.range.end.line - .range.start.line > 50)'

**Deep Nesting**
```bash
ast-grep -p 'function $NAME($$$) { $$$ }' --lang js --json | jq '.[] | select(.range.end.line - .range.start.line > 50)'

**深层嵌套**
```bash

Nested if statements (4+ levels)

Nested if statements (4+ levels)

ast-grep -p 'if ($A) { if ($B) { if ($C) { if ($D) { $$$ } } } }' --lang js

**Large Parameter Lists**
```bash
ast-grep -p 'function $NAME($A, $B, $C, $D, $E, $$$)' --lang js
Cyclomatic Complexity Indicators
bash
undefined
ast-grep -p 'if ($A) { if ($B) { if ($C) { if ($D) { $$$ } } } }' --lang js

**过长参数列表**
```bash
ast-grep -p 'function $NAME($A, $B, $C, $D, $E, $$$)' --lang js
圈复杂度指标
bash
undefined

Multiple conditionals in single function

Multiple conditionals in single function

ast-grep -p 'if ($$$) { $$$ } else if ($$$) { $$$ } else if ($$$) { $$$ }' --lang js
undefined
ast-grep -p 'if ($$$) { $$$ } else if ($$$) { $$$ } else if ($$$) { $$$ }' --lang js
undefined

6. React/Pinia Store Patterns

6. React/Pinia Store 模式

Direct State Mutation (Pinia)
bash
undefined
直接修改Pinia状态
bash
undefined

Direct store state mutation outside actions

Direct store state mutation outside actions

ast-grep -p '$STORE.$STATE = $VALUE' --lang js

**Missing Dependencies in useEffect**
```bash
ast-grep -p 'useEffect(() => { $$$ }, [])' --lang jsx
ast-grep -p '$STORE.$STATE = $VALUE' --lang js

**useEffect 缺失依赖项**
```bash
ast-grep -p 'useEffect(() => { $$$ }, [])' --lang jsx

Check if variables used inside are in dependency array

Check if variables used inside are in dependency array


**Inline Functions in JSX**
```bash
ast-grep -p '<$COMPONENT onClick={() => $$$} />' --lang jsx
ast-grep -p '<$COMPONENT onChange={() => $$$} />' --lang jsx

**JSX中的内联函数**
```bash
ast-grep -p '<$COMPONENT onClick={() => $$$} />' --lang jsx
ast-grep -p '<$COMPONENT onChange={() => $$$} />' --lang jsx

7. Memory & Performance

7. 内存与性能

Event Listeners Without Cleanup
bash
ast-grep -p 'addEventListener($EVENT, $HANDLER)' --lang js
未清理的事件监听器
bash
ast-grep -p 'addEventListener($EVENT, $HANDLER)' --lang js

Check for corresponding removeEventListener

Check for corresponding removeEventListener


**setInterval Without Cleanup**
```bash
ast-grep -p 'setInterval($$$)' --lang js

**未清理的setInterval**
```bash
ast-grep -p 'setInterval($$$)' --lang js

Check for clearInterval

Check for clearInterval


**Large Arrays in Computed/Memos**
```bash
ast-grep -p 'computed(() => $ARRAY.filter($$$))' --lang js
ast-grep -p 'useMemo(() => $ARRAY.filter($$$), [$$$])' --lang jsx

**计算属性/Memo中的大型数组**
```bash
ast-grep -p 'computed(() => $ARRAY.filter($$$))' --lang js
ast-grep -p 'useMemo(() => $ARRAY.filter($$$), [$$$])' --lang jsx

8. Security Concerns

8. 安全隐患

eval Usage
bash
ast-grep -p 'eval($$$)' --lang js
ast-grep -p 'new Function($$$)' --lang js
innerHTML Assignment (XSS Risk)
bash
ast-grep -p '$ELEM.innerHTML = $$$' --lang js
ast-grep -p 'dangerouslySetInnerHTML={{ __html: $$$ }}' --lang jsx
Hardcoded Secrets
bash
ast-grep -p "apiKey: '$$$'" --lang js
ast-grep -p "password = '$$$'" --lang js
ast-grep -p "secret: '$$$'" --lang js
SQL String Concatenation
bash
ast-grep -p '"SELECT * FROM " + $VAR' --lang js
ast-grep -p '`SELECT * FROM ${$VAR}`' --lang js
使用eval
bash
ast-grep -p 'eval($$$)' --lang js
ast-grep -p 'new Function($$$)' --lang js
innerHTML赋值(XSS风险)
bash
ast-grep -p '$ELEM.innerHTML = $$$' --lang js
ast-grep -p 'dangerouslySetInnerHTML={{ __html: $$$ }}' --lang jsx
硬编码密钥
bash
ast-grep -p "apiKey: '$$$'" --lang js
ast-grep -p "password = '$$$'" --lang js
ast-grep -p "secret: '$$$'" --lang js
SQL字符串拼接
bash
ast-grep -p '"SELECT * FROM " + $VAR' --lang js
ast-grep -p '`SELECT * FROM ${$VAR}`' --lang js

9. Python Anti-patterns

9. Python 反模式

Bare Except
bash
ast-grep -p 'except: $$$' --lang py
Mutable Default Arguments
bash
ast-grep -p 'def $FUNC($ARG=[])' --lang py
ast-grep -p 'def $FUNC($ARG={})' --lang py
Global Variable Usage
bash
ast-grep -p 'global $VAR' --lang py
Type: ignore Without Reason
bash
undefined
裸Except语句
bash
ast-grep -p 'except: $$$' --lang py
可变默认参数
bash
ast-grep -p 'def $FUNC($ARG=[])' --lang py
ast-grep -p 'def $FUNC($ARG={})' --lang py
全局变量使用
bash
ast-grep -p 'global $VAR' --lang py
无理由的Type: ignore
bash
undefined

Search in comments via grep

Search in comments via grep

grep -r "# type: ignore$" --include="*.py"
undefined
grep -r "# type: ignore$" --include="*.py"
undefined

Parallel Analysis Strategy

并行分析策略

When analyzing a codebase, launch multiple agents in parallel to maximize efficiency:
分析代码库时,应启动多个Agent并行执行以最大化效率:

Agent Delegation Pattern

Agent委托模式

markdown
1. **Language Detection Agent** (Explore)
   - Detect project languages and frameworks
   - Identify relevant file patterns

2. **JavaScript/TypeScript Agent** (code-analysis or Explore)
   - JS anti-patterns
   - TypeScript quality issues
   - Async/Promise patterns

3. **Framework-Specific Agent** (code-analysis or Explore)
   - Vue 3 anti-patterns (if Vue detected)
   - React anti-patterns (if React detected)
   - Pinia/Redux patterns (if detected)

4. **Security Agent** (security-audit)
   - Security concerns
   - Hardcoded values
   - Injection risks

5. **Complexity Agent** (code-analysis or Explore)
   - Code complexity metrics
   - Long functions
   - Deep nesting

6. **Python Agent** (if Python detected)
   - Python anti-patterns
   - Type annotation issues
markdown
1. **语言检测Agent** (Explore)
   - Detect project languages and frameworks
   - Identify relevant file patterns

2. **JavaScript/TypeScript Agent** (code-analysis or Explore)
   - JS anti-patterns
   - TypeScript quality issues
   - Async/Promise patterns

3. **框架专属Agent** (code-analysis or Explore)
   - Vue 3 anti-patterns (if Vue detected)
   - React anti-patterns (if React detected)
   - Pinia/Redux patterns (if detected)

4. **安全Agent** (security-audit)
   - Security concerns
   - Hardcoded values
   - Injection risks

5. **复杂度Agent** (code-analysis or Explore)
   - Code complexity metrics
   - Long functions
   - Deep nesting

6. **Python Agent** (if Python detected)
   - Python anti-patterns
   - Type annotation issues

Consolidation

结果整合

After parallel analysis completes:
  1. Aggregate findings by severity (critical, high, medium, low)
  2. Group by category (security, performance, maintainability)
  3. Provide actionable remediation suggestions
  4. Prioritize fixes based on impact
并行分析完成后:
  1. 按严重程度(关键、高、中、低)汇总发现的问题
  2. 按类别(安全、性能、可维护性)分组
  3. 提供可落地的修复建议
  4. 根据影响优先级排序修复项

YAML Rule Examples

YAML规则示例

Complete Anti-pattern Rule

完整反模式规则

yaml
id: no-empty-catch
language: JavaScript
severity: warning
message: Empty catch block suppresses errors silently
note: |
  Empty catch blocks hide errors and make debugging difficult.
  Either log the error, handle it specifically, or re-throw.

rule:
  pattern: try { $$$ } catch ($E) { }

fix: |
  try { $$$ } catch ($E) {
    console.error('Error:', $E);
    throw $E;
  }

files:
  - 'src/**/*.js'
  - 'src/**/*.ts'
ignores:
  - '**/*.test.js'
  - '**/node_modules/**'
yaml
id: no-empty-catch
language: JavaScript
severity: warning
message: Empty catch block suppresses errors silently
note: |
  Empty catch blocks hide errors and make debugging difficult.
  Either log the error, handle it specifically, or re-throw.

rule:
  pattern: try { $$$ } catch ($E) { }

fix: |
  try { $$$ } catch ($E) {
    console.error('Error:', $E);
    throw $E;
  }

files:
  - 'src/**/*.js'
  - 'src/**/*.ts'
ignores:
  - '**/*.test.js'
  - '**/node_modules/**'

Vue Props Mutation Rule

Vue Props修改规则

yaml
id: no-props-mutation
language: JavaScript
severity: error
message: Never mutate props directly - use emit or local copy

rule:
  all:
    - pattern: props.$PROP = $VALUE
    - inside:
        kind: function_declaration

note: |
  Props should be treated as immutable. To modify data:
  1. Emit an event to parent: emit('update:propName', newValue)
  2. Create a local ref: const local = ref(props.propName)
yaml
id: no-props-mutation
language: JavaScript
severity: error
message: Never mutate props directly - use emit or local copy

rule:
  all:
    - pattern: props.$PROP = $VALUE
    - inside:
        kind: function_declaration

note: |
  Props should be treated as immutable. To modify data:
  1. Emit an event to parent: emit('update:propName', newValue)
  2. Create a local ref: const local = ref(props.propName)

Integration with Commands

与命令的集成

This skill is designed to work with the
/code:antipatterns
command, which:
  1. Detects project language stack
  2. Launches parallel specialized agents
  3. Consolidates findings into prioritized report
  4. Suggests automated fixes where possible
本技能专为配合
/code:antipatterns
命令设计,该命令可:
  1. 检测项目技术栈
  2. 启动并行的专业Agent
  3. 将分析结果整合为优先级明确的报告
  4. 在可能的情况下提供自动化修复建议

Best Practices for Analysis

分析最佳实践

  1. Start with language detection - Run appropriate patterns for detected languages
  2. Use parallel agents - Don't sequentially analyze; delegate to specialized agents
  3. Prioritize by severity - Security issues first, then correctness, then style
  4. Provide fixes - Don't just identify problems; suggest solutions
  5. Consider context - Some "anti-patterns" are acceptable in specific contexts
  6. Check test files separately - Different standards may apply to test code
  1. 从语言检测开始 - 针对检测到的语言运行相应的规则
  2. 使用并行Agent - 不要按顺序分析,而是委托给专业Agent
  3. 按严重程度优先级处理 - 优先处理安全问题,其次是正确性问题,最后是风格问题
  4. 提供修复方案 - 不仅要识别问题,还要给出解决方案
  5. 考虑上下文 - 某些“反模式”在特定场景下是可接受的
  6. 单独检查测试文件 - 测试代码可能适用不同的标准

Severity Levels

严重程度等级

SeverityDescriptionExamples
CriticalSecurity vulnerabilities, data loss riskeval(), SQL injection, hardcoded secrets
HighBugs, incorrect behaviorProps mutation, unhandled promises, empty catch
MediumMaintainability issuesMagic numbers, deep nesting, large functions
LowStyle/preferencevar usage, console.log, inline functions
严重程度描述示例
关键安全漏洞、数据丢失风险eval()、SQL注入、硬编码密钥
缺陷、行为异常Props修改、未处理Promise、空Catch块
可维护性问题魔法值、深层嵌套、长函数
风格/偏好问题var使用、console.log、内联函数

Resources

参考资源