code-antipatterns-analysis
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode 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
undefinedNested 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
**魔法值**
```bashMagic 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 jsConsole Statements (Debug Leftovers)
bash
ast-grep -p 'console.log($$$)' --lang js
ast-grep -p 'console.debug($$$)' --lang js
ast-grep -p 'console.warn($$$)' --lang jsUse let/const for Variable Declarations
bash
ast-grep -p 'var $VAR = $$$' --lang jsast-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 js2. Vue 3 Anti-patterns
2. Vue 3 反模式
Props Mutation
yaml
undefinedProps 直接修改
yaml
undefinedYAML 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
```bashid: vue-props-mutation
language: JavaScript
message: Use computed properties or emit events to update props
rule:
pattern: props.$PROP = $VALUE
```bashDirect prop assignment
Direct prop assignment
ast-grep -p 'props.$PROP = $VALUE' --lang js
**Missing Keys in v-for**
```bashast-grep -p 'props.$PROP = $VALUE' --lang js
**v-for 缺失Key**
```bashSearch 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**
```bashFind 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**
```bashast-grep -p 'defineComponent({ setup($$$) { $$$ } })' --lang js
**响应式状态问题**
```bashDestructuring 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
undefinedast-grep -p 'const { $$$PROPS } = toRefs($REACTIVE)' --lang js
undefined3. TypeScript Quality Issues
3. TypeScript 质量问题
Excessive Usage
anybash
ast-grep -p ': any' --lang ts
ast-grep -p 'as any' --lang ts
ast-grep -p '<any>' --lang tsNon-null Assertions
bash
ast-grep -p '$VAR!' --lang ts
ast-grep -p '$VAR!.$PROP' --lang tsType Assertions Instead of Guards
bash
ast-grep -p '$VAR as $TYPE' --lang tsMissing Return Types
bash
undefined过度使用类型
anybash
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
undefinedFunctions 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
undefinedundefined4. Async/Promise Patterns
4. Async/Promise 模式
Unhandled Promises
bash
undefined未处理的Promise
bash
undefinedPromise 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 jsPromise Constructor Anti-pattern
bash
undefinedast-grep -p '$PROMISE_RETURNING()' --lang ts
**嵌套回调(厄运金字塔)**
```bash
ast-grep -p '$F1($$$, function($$$) { $F2($$$, function($$$) { $F3($$$, function($$$) { $$$ }) }) })' --lang jsPromise构造函数反模式
bash
undefinedWrapping 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
undefinedast-grep -p 'new Promise(($RESOLVE, $REJECT) => { $ASYNC_FUNC($$$).then($$$) })' --lang js
undefined5. Code Complexity
5. 代码复杂度
Long Functions (Manual Review)
bash
undefined长函数(人工评审)
bash
undefinedFind 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**
```bashast-grep -p 'function $NAME($$$) { $$$ }' --lang js --json | jq '.[] | select(.range.end.line - .range.start.line > 50)'
**深层嵌套**
```bashNested 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 jsCyclomatic Complexity Indicators
bash
undefinedast-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
undefinedMultiple conditionals in single function
Multiple conditionals in single function
ast-grep -p 'if ($$$) { $$$ } else if ($$$) { $$$ } else if ($$$) { $$$ }' --lang js
undefinedast-grep -p 'if ($$$) { $$$ } else if ($$$) { $$$ } else if ($$$) { $$$ }' --lang js
undefined6. React/Pinia Store Patterns
6. React/Pinia Store 模式
Direct State Mutation (Pinia)
bash
undefined直接修改Pinia状态
bash
undefinedDirect 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 jsxast-grep -p '$STORE.$STATE = $VALUE' --lang js
**useEffect 缺失依赖项**
```bash
ast-grep -p 'useEffect(() => { $$$ }, [])' --lang jsxCheck 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 jsx7. Memory & Performance
7. 内存与性能
Event Listeners Without Cleanup
bash
ast-grep -p 'addEventListener($EVENT, $HANDLER)' --lang js未清理的事件监听器
bash
ast-grep -p 'addEventListener($EVENT, $HANDLER)' --lang jsCheck for corresponding removeEventListener
Check for corresponding removeEventListener
**setInterval Without Cleanup**
```bash
ast-grep -p 'setInterval($$$)' --lang js
**未清理的setInterval**
```bash
ast-grep -p 'setInterval($$$)' --lang jsCheck 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 jsx8. Security Concerns
8. 安全隐患
eval Usage
bash
ast-grep -p 'eval($$$)' --lang js
ast-grep -p 'new Function($$$)' --lang jsinnerHTML Assignment (XSS Risk)
bash
ast-grep -p '$ELEM.innerHTML = $$$' --lang js
ast-grep -p 'dangerouslySetInnerHTML={{ __html: $$$ }}' --lang jsxHardcoded Secrets
bash
ast-grep -p "apiKey: '$$$'" --lang js
ast-grep -p "password = '$$$'" --lang js
ast-grep -p "secret: '$$$'" --lang jsSQL 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 jsinnerHTML赋值(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 jsSQL字符串拼接
bash
ast-grep -p '"SELECT * FROM " + $VAR' --lang js
ast-grep -p '`SELECT * FROM ${$VAR}`' --lang js9. Python Anti-patterns
9. Python 反模式
Bare Except
bash
ast-grep -p 'except: $$$' --lang pyMutable Default Arguments
bash
ast-grep -p 'def $FUNC($ARG=[])' --lang py
ast-grep -p 'def $FUNC($ARG={})' --lang pyGlobal Variable Usage
bash
ast-grep -p 'global $VAR' --lang pyType: 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
undefinedSearch in comments via grep
Search in comments via grep
grep -r "# type: ignore$" --include="*.py"
undefinedgrep -r "# type: ignore$" --include="*.py"
undefinedParallel 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 issuesmarkdown
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 issuesConsolidation
结果整合
After parallel analysis completes:
- Aggregate findings by severity (critical, high, medium, low)
- Group by category (security, performance, maintainability)
- Provide actionable remediation suggestions
- Prioritize fixes based on impact
并行分析完成后:
- 按严重程度(关键、高、中、低)汇总发现的问题
- 按类别(安全、性能、可维护性)分组
- 提供可落地的修复建议
- 根据影响优先级排序修复项
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 command, which:
/code:antipatterns- Detects project language stack
- Launches parallel specialized agents
- Consolidates findings into prioritized report
- Suggests automated fixes where possible
本技能专为配合命令设计,该命令可:
/code:antipatterns- 检测项目技术栈
- 启动并行的专业Agent
- 将分析结果整合为优先级明确的报告
- 在可能的情况下提供自动化修复建议
Best Practices for Analysis
分析最佳实践
- Start with language detection - Run appropriate patterns for detected languages
- Use parallel agents - Don't sequentially analyze; delegate to specialized agents
- Prioritize by severity - Security issues first, then correctness, then style
- Provide fixes - Don't just identify problems; suggest solutions
- Consider context - Some "anti-patterns" are acceptable in specific contexts
- Check test files separately - Different standards may apply to test code
- 从语言检测开始 - 针对检测到的语言运行相应的规则
- 使用并行Agent - 不要按顺序分析,而是委托给专业Agent
- 按严重程度优先级处理 - 优先处理安全问题,其次是正确性问题,最后是风格问题
- 提供修复方案 - 不仅要识别问题,还要给出解决方案
- 考虑上下文 - 某些“反模式”在特定场景下是可接受的
- 单独检查测试文件 - 测试代码可能适用不同的标准
Severity Levels
严重程度等级
| Severity | Description | Examples |
|---|---|---|
| Critical | Security vulnerabilities, data loss risk | eval(), SQL injection, hardcoded secrets |
| High | Bugs, incorrect behavior | Props mutation, unhandled promises, empty catch |
| Medium | Maintainability issues | Magic numbers, deep nesting, large functions |
| Low | Style/preference | var usage, console.log, inline functions |
| 严重程度 | 描述 | 示例 |
|---|---|---|
| 关键 | 安全漏洞、数据丢失风险 | eval()、SQL注入、硬编码密钥 |
| 高 | 缺陷、行为异常 | Props修改、未处理Promise、空Catch块 |
| 中 | 可维护性问题 | 魔法值、深层嵌套、长函数 |
| 低 | 风格/偏好问题 | var使用、console.log、内联函数 |
Resources
参考资源
- ast-grep Documentation: https://ast-grep.github.io/
- ast-grep Playground: https://ast-grep.github.io/playground.html
- OWASP Top 10: https://owasp.org/www-project-top-ten/
- Clean Code Principles: https://clean-code-developer.com/
- ast-grep 文档: https://ast-grep.github.io/
- ast-grep 在线 playground: https://ast-grep.github.io/playground.html
- OWASP Top 10: https://owasp.org/www-project-top-ten/
- Clean Code 原则: https://clean-code-developer.com/