code-smell-detector
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode Smell Detector Skill
代码坏味道检测Skill
Purpose
用途
This skill identifies anti-patterns that violate amplihack's development philosophy and provides constructive, specific fixes. It ensures code maintains ruthless simplicity, modular design, and zero-BS implementations.
本Skill用于识别违反Amplihack开发哲学的代码反模式,并提供具有建设性的具体修复方案。它确保代码保持极致简洁、模块化设计以及零冗余实现。
When to Use This Skill
何时使用本Skill
- Code review: Identify violations before merging
- Refactoring: Find opportunities to simplify and improve code quality
- New module creation: Catch issues early in development
- Philosophy compliance: Ensure code aligns with amplihack principles
- Learning: Understand why patterns are problematic and how to fix them
- Mentoring: Educate team members on philosophy-aligned code patterns
- 代码审查:在合并前识别违规问题
- 代码重构:寻找简化和提升代码质量的机会
- 新模块创建:在开发早期发现问题
- 哲学合规性检查:确保代码符合Amplihack原则
- 学习参考:理解不良模式的问题所在及修复方法
- 团队指导:向团队成员传授符合哲学理念的代码模式
Core Philosophy Reference
核心哲学参考
Amplihack Development Philosophy focuses on:
- Ruthless Simplicity: Every abstraction must justify its existence
- Modular Design (Bricks & Studs): Self-contained modules with clear connection points
- Zero-BS Implementation: No stubs, no placeholders, only working code
- Single Responsibility: Each module/function has ONE clear job
Amplihack开发哲学核心关注:
- 极致简洁:每一层抽象都必须证明其存在的必要性
- 模块化设计(积木式架构):具备清晰连接点的独立模块
- 零冗余实现:无存根、无占位符,仅保留可运行代码
- 单一职责:每个模块/函数仅有一项明确职责
Code Smells Detected
可检测的代码坏味道
1. Over-Abstraction
1. 过度抽象
What It Is: Unnecessary layers of abstraction, generic base classes, or interfaces that don't provide clear value.
Why It's Bad: Violates "ruthless simplicity" - adds complexity without proportional benefit. Makes code harder to understand and maintain.
Red Flags:
- Abstract base classes with only one implementation
- Generic helper classes that do very little
- Deep inheritance hierarchies (3+ levels)
- Interfaces for single implementations
- Over-parameterized functions
Example - SMELL:
python
undefined定义:无意义的抽象层、通用基类或接口,无法提供明确价值。
危害:违反"极致简洁"原则——增加复杂度却未带来对等收益,使代码更难理解和维护。
预警信号:
- 仅有一个实现类的抽象基类
- 功能极少的通用辅助类
- 深度继承层级(3层及以上)
- 仅有一个实现的接口
- 参数过度冗余的函数
示例 - 坏味道:
python
undefinedBAD: Over-abstracted
BAD: Over-abstracted
class DataProcessor(ABC):
@abstractmethod
def process(self, data):
pass
class SimpleDataProcessor(DataProcessor):
def process(self, data):
return data * 2
**Example - FIXED**:
```pythonclass DataProcessor(ABC):
@abstractmethod
def process(self, data):
pass
class SimpleDataProcessor(DataProcessor):
def process(self, data):
return data * 2
**示例 - 修复后**:
```pythonGOOD: Direct implementation
GOOD: Direct implementation
def process_data(data):
"""Process data by doubling it."""
return data * 2
**Detection Checklist**:
- [ ] Abstract classes with only 1-2 concrete implementations
- [ ] Generic utility classes that don't encapsulate state
- [ ] Type hierarchies deeper than 2 levels
- [ ] Mixins solving single problems
**Fix Strategy**:
1. Identify what the abstraction solves
2. Check if you really need multiple implementations now
3. Delete the abstraction - use direct implementation
4. If multiple implementations needed later, refactor then
5. Principle: Avoid future-proofing
---def process_data(data):
"""Process data by doubling it."""
return data * 2
**检测清单**:
- [ ] 仅有1-2个具体实现的抽象类
- [ ] 未封装状态的通用工具类
- [ ] 层级深度超过2的类型继承链
- [ ] 仅解决单一问题的Mixin类
**修复策略**:
1. 明确抽象要解决的问题
2. 确认当前是否真的需要多个实现
3. 删除抽象,采用直接实现方式
4. 若后续需要多个实现,届时再进行重构
5. 原则:避免过度超前设计
---2. Complex Inheritance
2. 复杂继承
What It Is: Deep inheritance chains, multiple inheritance, or convoluted class hierarchies that obscure code flow.
Why It's Bad: Makes code hard to follow, creates tight coupling, violates simplicity principle. Who does what becomes unclear.
Red Flags:
- 3+ levels of inheritance (GrandparentClass -> ParentClass -> ChildClass)
- Multiple inheritance from non-interface classes
- Inheritance used for code reuse instead of composition
- Overriding multiple levels of methods
- "Mixin" classes for cross-cutting concerns
Example - SMELL:
python
undefined定义:深度继承链、多重继承或混乱的类层级,导致代码流程模糊。
危害:使代码难以追踪,造成紧耦合,违反简洁原则,职责划分不清晰。
预警信号:
- 3层及以上的继承层级(祖父类 -> 父类 -> 子类)
- 从非接口类进行多重继承
- 为代码复用而使用继承而非组合
- 多层级方法重写
- 用于横切关注点的"Mixin"类
示例 - 坏味道:
python
undefinedBAD: Complex inheritance
BAD: Complex inheritance
class Entity:
def save(self): pass
def load(self): pass
class TimestampedEntity(Entity):
def add_timestamp(self): pass
class AuditableEntity(TimestampedEntity):
def audit_log(self): pass
class User(AuditableEntity):
def authenticate(self): pass
**Example - FIXED**:
```pythonclass Entity:
def save(self): pass
def load(self): pass
class TimestampedEntity(Entity):
def add_timestamp(self): pass
class AuditableEntity(TimestampedEntity):
def audit_log(self): pass
class User(AuditableEntity):
def authenticate(self): pass
**示例 - 修复后**:
```pythonGOOD: Composition over inheritance
GOOD: Composition over inheritance
class User:
def init(self, storage, timestamp_service, audit_log):
self.storage = storage
self.timestamps = timestamp_service
self.audit = audit_log
def save(self):
self.storage.save(self)
self.timestamps.record()
self.audit.log("saved user")
**Detection Checklist**:
- [ ] Inheritance depth > 2 levels
- [ ] Multiple inheritance from concrete classes
- [ ] Methods overridden at multiple inheritance levels
- [ ] Inheritance hierarchy with no code reuse
**Fix Strategy**:
1. Use composition instead of inheritance
2. Pass services as constructor arguments
3. Each class handles its own responsibility
4. Easier to test, understand, and modify
---class User:
def init(self, storage, timestamp_service, audit_log):
self.storage = storage
self.timestamps = timestamp_service
self.audit = audit_log
def save(self):
self.storage.save(self)
self.timestamps.record()
self.audit.log("saved user")
**检测清单**:
- [ ] 继承深度超过2层
- [ ] 从具体类进行多重继承
- [ ] 在多个继承层级重写方法
- [ ] 无代码复用的继承层级
**修复策略**:
1. 使用组合替代继承
2. 通过构造函数参数传入服务
3. 每个类仅处理自身职责
4. 更易于测试、理解和修改
---3. Large Functions (>50 Lines)
3. 超长函数(超过50行)
What It Is: Functions that do too many things and are difficult to understand, test, and modify.
Why It's Bad: Violates single responsibility, makes testing harder, increases bug surface area, reduces code reusability.
Red Flags:
- Functions with >50 lines of code
- Multiple indentation levels (3+ nested if/for)
- Functions with 5+ parameters
- Functions that need scrolling to see all of them
- Complex logic that's hard to name
Example - SMELL:
python
undefined定义:职责过多、难以理解、测试和修改的函数。
危害:违反单一职责原则,增加测试难度,扩大bug出现范围,降低代码复用性。
预警信号:
- 代码行数超过50行的函数
- 多层缩进(3层及以上嵌套if/for)
- 参数数量超过5个的函数
- 需要滚动才能查看全部内容的函数
- 难以命名的复杂逻辑
示例 - 坏味道:
python
undefinedBAD: Large function doing multiple things
BAD: Large function doing multiple things
def process_user_data(user_dict, validate=True, save=True, notify=True, log=True):
if validate:
if not user_dict.get('email'):
raise ValueError("Email required")
if not '@' in user_dict['email']:
raise ValueError("Invalid email")
user = User(
name=user_dict['name'],
email=user_dict['email'],
phone=user_dict['phone']
)
if save:
db.save(user)
if notify:
email_service.send(user.email, "Welcome!")
if log:
logger.info(f"User {user.name} created")
# ... 30+ more lines of mixed concerns
return user
**Example - FIXED**:
```pythondef process_user_data(user_dict, validate=True, save=True, notify=True, log=True):
if validate:
if not user_dict.get('email'):
raise ValueError("Email required")
if not '@' in user_dict['email']:
raise ValueError("Invalid email")
user = User(
name=user_dict['name'],
email=user_dict['email'],
phone=user_dict['phone']
)
if save:
db.save(user)
if notify:
email_service.send(user.email, "Welcome!")
if log:
logger.info(f"User {user.name} created")
# ... 30+ more lines of mixed concerns
return user
**示例 - 修复后**:
```pythonGOOD: Separated concerns
GOOD: Separated concerns
def validate_user_data(user_dict):
"""Validate user data structure."""
if not user_dict.get('email'):
raise ValueError("Email required")
if '@' not in user_dict['email']:
raise ValueError("Invalid email")
def create_user(user_dict):
"""Create user object from data."""
return User(
name=user_dict['name'],
email=user_dict['email'],
phone=user_dict['phone']
)
def process_user_data(user_dict):
"""Orchestrate user creation workflow."""
validate_user_data(user_dict)
user = create_user(user_dict)
db.save(user)
email_service.send(user.email, "Welcome!")
logger.info(f"User {user.name} created")
return user
**Detection Checklist**:
- [ ] Function body >50 lines
- [ ] 3+ levels of nesting
- [ ] Multiple unrelated operations
- [ ] Hard to name succinctly
- [ ] 5+ parameters
**Fix Strategy**:
1. Extract helper functions for each concern
2. Give each function a clear, single purpose
3. Compose small functions into larger workflows
4. Each function should fit on one screen
5. Easy to name = usually doing one thing
---def validate_user_data(user_dict):
"""Validate user data structure."""
if not user_dict.get('email'):
raise ValueError("Email required")
if '@' not in user_dict['email']:
raise ValueError("Invalid email")
def create_user(user_dict):
"""Create user object from data."""
return User(
name=user_dict['name'],
email=user_dict['email'],
phone=user_dict['phone']
)
def process_user_data(user_dict):
"""Orchestrate user creation workflow."""
validate_user_data(user_dict)
user = create_user(user_dict)
db.save(user)
email_service.send(user.email, "Welcome!")
logger.info(f"User {user.name} created")
return user
**检测清单**:
- [ ] 函数体超过50行
- [ ] 3层及以上嵌套
- [ ] 包含多个无关操作
- [ ] 难以简洁命名
- [ ] 参数数量超过5个
**修复策略**:
1. 为每个关注点提取辅助函数
2. 为每个函数赋予明确的单一职责
3. 将小函数组合成大型工作流
4. 每个函数应能在一屏内显示
5. 易于命名通常意味着职责单一
---4. Tight Coupling
4. 紧耦合
What It Is: Modules/classes directly depend on concrete implementations instead of abstractions, making them hard to test and modify.
Why It's Bad: Changes in one module break others. Hard to test in isolation. Violates modularity principle.
Red Flags:
- Direct instantiation of classes inside functions ()
db = Database() - Deep attribute access ()
obj.service.repository.data - Hardcoded class names in conditionals
- Module imports everything from another module
- Circular dependencies between modules
Example - SMELL:
python
undefined定义:模块/类直接依赖具体实现而非抽象,导致难以测试和修改。
危害:一个模块的变更会影响其他模块,难以孤立测试,违反模块化原则。
预警信号:
- 在函数内部直接实例化类(如)
db = Database() - 深度属性访问(如)
obj.service.repository.data - 条件判断中硬编码类名
- 模块导入另一个模块的所有内容
- 模块间存在循环依赖
示例 - 坏味道:
python
undefinedBAD: Tight coupling
BAD: Tight coupling
class UserService:
def create_user(self, name, email):
db = Database() # Hardcoded dependency
user = db.save_user(name, email)
email_service = EmailService() # Hardcoded dependency
email_service.send(email, "Welcome!")
return user
def get_user(self, user_id):
db = Database()
return db.find_user(user_id)
**Example - FIXED**:
```pythonclass UserService:
def create_user(self, name, email):
db = Database() # Hardcoded dependency
user = db.save_user(name, email)
email_service = EmailService() # Hardcoded dependency
email_service.send(email, "Welcome!")
return user
def get_user(self, user_id):
db = Database()
return db.find_user(user_id)
**示例 - 修复后**:
```pythonGOOD: Loose coupling via dependency injection
GOOD: Loose coupling via dependency injection
class UserService:
def init(self, db, email_service):
self.db = db
self.email = email_service
def create_user(self, name, email):
user = self.db.save_user(name, email)
self.email.send(email, "Welcome!")
return user
def get_user(self, user_id):
return self.db.find_user(user_id)class UserService:
def init(self, db, email_service):
self.db = db
self.email = email_service
def create_user(self, name, email):
user = self.db.save_user(name, email)
self.email.send(email, "Welcome!")
return user
def get_user(self, user_id):
return self.db.find_user(user_id)Usage:
Usage:
user_service = UserService(db=PostgresDB(), email_service=SMTPService())
**Detection Checklist**:
- [ ] Class instantiation inside methods (`Service()`)
- [ ] Deep attribute chaining (3+ dots)
- [ ] Hardcoded class references
- [ ] Circular imports or dependencies
- [ ] Module can't be tested without other modules
**Fix Strategy**:
1. Accept dependencies as constructor parameters
2. Use dependency injection
3. Create test doubles (mocks) easily
4. Swap implementations without changing code
5. Each module is independently testable
---user_service = UserService(db=PostgresDB(), email_service=SMTPService())
**检测清单**:
- [ ] 在方法内部实例化类(如`Service()`)
- [ ] 深度属性链式访问(3个及以上点号)
- [ ] 硬编码类引用
- [ ] 循环导入或依赖
- [ ] 无法独立于其他模块测试的模块
**修复策略**:
1. 通过构造函数参数接收依赖
2. 使用依赖注入
3. 轻松创建测试替身(模拟对象)
4. 无需修改代码即可替换实现
5. 每个模块均可独立测试
---5. Missing __all__
Exports (Python)
__all__5. 缺失__all__
导出(Python)
__all__What It Is: Python modules that don't explicitly define their public interface via .
__all__Why It's Bad: Unclear what's public vs internal. Users import private implementation details. Violates the "stud" concept - unclear connection points.
Red Flags:
- No in
__all____init__.py - Modules expose internal functions/classes
- Users uncertain what to import
- Private names () still accessible
_function - Documentation doesn't match exports
Example - SMELL:
python
undefined定义:未通过明确定义公共接口的Python模块。
__all__危害:公共与内部接口界限模糊,用户可能导入私有实现细节,违反"积木式"架构中的明确连接点原则。
预警信号:
- 中无
__init__.py定义__all__ - 模块暴露内部函数/类
- 用户不确定应导入哪些内容
- 私有名称(如)仍可被访问
_function - 文档与导出内容不匹配
示例 - 坏味道:
python
undefinedBAD: No all - unclear public interface
BAD: No all - unclear public interface
module/init.py
module/init.py
from .core import process_data, _internal_helper
from .utils import validate_input, LOG_LEVEL
from .core import process_data, _internal_helper
from .utils import validate_input, LOG_LEVEL
What should users import? All of it? Only some?
What should users import? All of it? Only some?
**Example - FIXED**:
```python
**示例 - 修复后**:
```pythonGOOD: Clear public interface via all
GOOD: Clear public interface via all
module/init.py
module/init.py
from .core import process_data
from .utils import validate_input
all = ['process_data', 'validate_input']
from .core import process_data
from .utils import validate_input
all = ['process_data', 'validate_input']
Users know exactly what's public and what to use
Users know exactly what's public and what to use
**Detection Checklist**:
- [ ] Missing `__all__` in `__init__.py`
- [ ] Internal functions (prefixed with `_`) exposed
- [ ] Unclear what's "public API"
- [ ] All imports at module level
**Fix Strategy**:
1. Add `__all__` to every `__init__.py`
2. List ONLY the public functions/classes
3. Prefix internal implementation with `_`
4. Update documentation to match `__all__`
5. Clear = users know exactly what to use
---
**检测清单**:
- [ ] `__init__.py`中缺失`__all__`
- [ ] 暴露内部函数(以`_`为前缀)
- [ ] "公共API"界限模糊
- [ ] 模块级导入所有内容
**修复策略**:
1. 为每个`__init__.py`添加`__all__`
2. 仅列出公共函数/类
3. 为内部实现添加`_`前缀
4. 更新文档以匹配`__all__`内容
5. 清晰明确 = 用户知道该使用什么
---Analysis Process
分析流程
Step 1: Scan Code Structure
步骤1:扫描代码结构
- Review file organization and module boundaries
- Identify inheritance hierarchies
- Scan for large functions (count lines)
- Note presence/absence
__all__ - Check for tight coupling patterns
- 审查文件组织和模块边界
- 识别继承层级
- 扫描超长函数(统计行数)
- 记录的存在情况
__all__ - 检查紧耦合模式
Step 2: Analyze Each Smell
步骤2:分析每个坏味道
For each potential issue:
- Confirm it violates philosophy
- Measure severity (critical/major/minor)
- Find specific line numbers
- Note impact on system
针对每个潜在问题:
- 确认是否违反哲学原则
- 评估严重程度(严重/主要/次要)
- 定位具体行号
- 记录对系统的影响
Step 3: Generate Fixes
步骤3:生成修复方案
For each smell found:
- Provide clear explanation of WHY it's bad
- Show BEFORE code
- Show AFTER code with detailed comments
- Explain philosophy principle violated
- Give concrete refactoring steps
针对每个发现的坏味道:
- 清晰解释其危害
- 展示修复前代码
- 展示带详细注释的修复后代码
- 解释违反的哲学原则
- 提供具体的重构步骤
Step 4: Create Report
步骤4:创建报告
- List all smells found
- Prioritize by severity/impact
- Include specific examples
- Provide actionable fixes
- Reference philosophy docs
- 列出所有发现的坏味道
- 按严重程度/影响优先级排序
- 包含具体示例
- 提供可执行的修复方案
- 参考哲学文档
Detection Rules
检测规则
Rule 1: Abstract Base Classes
规则1:抽象基类
Check: with exactly 1 concrete implementation
class X(ABC)python
undefined检查:仅有1个具体实现
class X(ABC)python
undefinedBAD pattern detection
BAD pattern detection
- Count implementations of abstract class
- If count <= 2 and not used as interface: FLAG
**Fix**: Remove abstraction, use direct implementation- Count implementations of abstract class
- If count <= 2 and not used as interface: FLAG
**修复**:移除抽象,采用直接实现Rule 2: Inheritance Depth
规则2:继承深度
Check: Class hierarchy depth
python
undefined检查:类层级深度
python
undefinedBAD pattern detection
BAD pattern detection
- Follow inheritance chain: class -> parent -> grandparent...
- If depth > 2: FLAG
**Fix**: Use composition instead- Follow inheritance chain: class -> parent -> grandparent...
- If depth > 2: FLAG
**修复**:使用组合替代Rule 3: Function Line Count
规则3:函数行数统计
Check: All function bodies
python
undefined检查:所有函数体
python
undefinedBAD pattern detection
BAD pattern detection
- Count lines in function (excluding docstring)
- If > 50 lines: FLAG
- If > 3 nesting levels: FLAG
**Fix**: Extract helper functions- Count lines in function (excluding docstring)
- If > 50 lines: FLAG
- If > 3 nesting levels: FLAG
**修复**:提取辅助函数Rule 4: Dependency Instantiation
规则4:依赖实例化
Check: Class instantiation inside methods/functions
python
undefined检查:方法/函数内部的类实例化
python
undefinedBAD pattern detection
BAD pattern detection
- Search for "= ServiceName()" inside methods
- If found: FLAG
**Fix**: Pass as constructor argument- Search for "= ServiceName()" inside methods
- If found: FLAG
**修复**:通过构造函数参数传入Rule 5: Missing all
规则5:缺失__all__
__all__Check: Python modules
python
undefined检查:Python模块
python
undefinedBAD pattern detection
BAD pattern detection
- Look for all definition
- If missing: FLAG
- If all incomplete: FLAG
**Fix**: Define explicit `__all__`
---- Look for all definition
- If missing: FLAG
- If all incomplete: FLAG
**修复**:明确定义`__all__`
---Common Code Smells & Quick Fixes
常见代码坏味道与快速修复
Smell: "Utility Class" Holder
坏味道:"工具类"容器
python
undefinedpython
undefinedBAD
BAD
class StringUtils:
@staticmethod
def clean(s):
return s.strip().lower()
**Fix**: Use direct function
```pythonclass StringUtils:
@staticmethod
def clean(s):
return s.strip().lower()
**修复**:使用直接函数
```pythonGOOD
GOOD
def clean_string(s):
return s.strip().lower()
---def clean_string(s):
return s.strip().lower()
---Smell: "Manager" Class
坏味道:"管理器"类
python
undefinedpython
undefinedBAD
BAD
class UserManager:
def create(self): pass
def update(self): pass
def delete(self): pass
def validate(self): pass
def email(self): pass
**Fix**: Split into focused services
```pythonclass UserManager:
def create(self): pass
def update(self): pass
def delete(self): pass
def validate(self): pass
def email(self): pass
**修复**:拆分为专注的服务
```pythonGOOD
GOOD
class UserService:
def init(self, db, email):
self.db = db
self.email = email
def create(self): pass
def update(self): pass
def delete(self): passdef validate_user(user): pass
---class UserService:
def init(self, db, email):
self.db = db
self.email = email
def create(self): pass
def update(self): pass
def delete(self): passdef validate_user(user): pass
---Smell: God Function
坏味道:上帝函数
python
undefinedpython
undefinedBAD - 200 line function doing everything
BAD - 200 line function doing everything
def process_order(order_data, validate, save, notify, etc...):
# 200 lines mixing validation, transformation, DB, email, logging
**Fix**: Compose small functions
```pythondef process_order(order_data, validate, save, notify, etc...):
# 200 lines mixing validation, transformation, DB, email, logging
**修复**:组合小函数
```pythonGOOD
GOOD
def process_order(order_data):
validate_order(order_data)
order = create_order(order_data)
save_order(order)
notify_customer(order)
log_creation(order)
---def process_order(order_data):
validate_order(order_data)
order = create_order(order_data)
save_order(order)
notify_customer(order)
log_creation(order)
---Smell: Brittle Inheritance
坏味道:脆弱的继承
python
undefinedpython
undefinedBAD
BAD
class Base:
def work(self): pass
class Middle(Base):
def work(self):
return super().work()
class Derived(Middle):
def work(self):
return super().work() # Which work()?
**Fix**: Use clear, testable composition
```pythonclass Base:
def work(self): pass
class Middle(Base):
def work(self):
return super().work()
class Derived(Middle):
def work(self):
return super().work() # Which work()?
**修复**:使用清晰、可测试的组合
```pythonGOOD
GOOD
class Worker:
def init(self, validator, transformer):
self.validator = validator
self.transformer = transformer
def work(self, data):
self.validator.check(data)
return self.transformer.apply(data)
---class Worker:
def init(self, validator, transformer):
self.validator = validator
self.transformer = transformer
def work(self, data):
self.validator.check(data)
return self.transformer.apply(data)
---Smell: Hidden Dependencies
坏味道:隐藏依赖
python
undefinedpython
undefinedBAD
BAD
def fetch_data(user_id):
db = Database() # Where's this coming from?
return db.query(f"SELECT * FROM users WHERE id={user_id}")
**Fix**: Inject dependencies explicitly
```pythondef fetch_data(user_id):
db = Database() # Where's this coming from?
return db.query(f"SELECT * FROM users WHERE id={user_id}")
**修复**:显式注入依赖
```pythonGOOD
GOOD
def fetch_data(user_id, db):
return db.query(f"SELECT * FROM users WHERE id={user_id}")
def fetch_data(user_id, db):
return db.query(f"SELECT * FROM users WHERE id={user_id}")
Or in a class:
Or in a class:
class UserRepository:
def init(self, db):
self.db = db
def fetch(self, user_id):
return self.db.query(f"SELECT * FROM users WHERE id={user_id}")
---class UserRepository:
def init(self, db):
self.db = db
def fetch(self, user_id):
return self.db.query(f"SELECT * FROM users WHERE id={user_id}")
---Usage Examples
使用示例
Example 1: Review New Module
示例1:审查新模块
User: Review this new authentication module for code smells.
Claude:
1. Scans all Python files in module
2. Checks for each smell type
3. Finds:
- Abstract base class with 1 implementation
- Large 120-line authenticate() function
- Missing __all__ in __init__.py
4. Provides specific fixes with before/after code
5. Explains philosophy violations用户:审查这个新的认证模块是否存在代码坏味道。
Claude:
1. 扫描模块中的所有Python文件
2. 检查每种坏味道类型
3. 发现:
- 仅有1个实现的抽象基类
- 120行的超长authenticate()函数
- __init__.py中缺失__all__
4. 提供带修复前后代码的具体方案
5. 解释违反的哲学原则Example 2: Identify Tight Coupling
示例2:识别紧耦合
User: Find tight coupling in this user service.
Claude:
1. Traces all dependencies
2. Finds hardcoded Database() instantiation
3. Finds direct EmailService() creation
4. Shows dependency injection fix
5. Includes test example showing why it matters用户:找出这个用户服务中的紧耦合问题。
Claude:
1. 追踪所有依赖
2. 发现硬编码的Database()实例化
3. 发现直接创建EmailService()
4. 展示依赖注入修复方案
5. 包含测试示例说明其重要性Example 3: Simplify Inheritance
示例3:简化继承
User: This class hierarchy is too complex.
Claude:
1. Maps inheritance tree (finds 4 levels)
2. Shows each level doing what
3. Suggests composition approach
4. Provides before/after refactoring
5. Explains how it aligns with brick philosophy用户:这个类层级太复杂了。
Claude:
1. 绘制继承树(发现4层)
2. 展示每个层级的职责
3. 建议组合方式
4. 提供重构前后的代码
5. 解释如何符合积木式哲学Analysis Checklist
分析清单
Philosophy Compliance
哲学合规性
- No unnecessary abstractions
- Single responsibility per class/function
- Clear public interface ()
__all__ - Dependencies injected, not hidden
- Inheritance depth <= 2 levels
- Functions < 50 lines
- No dead code or stubs
- 无不必要的抽象
- 每个类/函数单一职责
- 清晰的公共接口()
__all__ - 依赖注入而非隐藏
- 继承深度≤2层
- 函数行数<50
- 无死代码或存根
Code Quality
代码质量
- Each function has one clear job
- Easy to understand at a glance
- Easy to test in isolation
- Easy to modify without breaking others
- Clear naming reflects responsibility
- 每个函数职责明确
- 一眼就能理解
- 易于孤立测试
- 修改时不易影响其他部分
- 命名清晰反映职责
Modularity
模块化
- Modules are independently testable
- Clear connection points ("studs")
- Loose coupling between modules
- Explicit dependencies
- 模块可独立测试
- 清晰的连接点("积木凸点")
- 模块间松耦合
- 依赖关系明确
Success Criteria for Review
审查成功标准
A code review using this skill should:
- Identify all violations of philosophy
- Provide specific line numbers
- Show before/after examples
- Explain WHY each is a problem
- Suggest concrete fixes
- Include test strategies
- Reference philosophy docs
- Prioritize by severity
- Be constructive and educational
- Help writer improve future code
使用本Skill进行的代码审查应:
- 识别所有违反哲学原则的问题
- 提供具体行号
- 展示修复前后示例
- 解释每个问题的危害
- 建议具体修复方案
- 包含测试策略
- 参考哲学文档
- 按严重程度排序
- 具有建设性和教育意义
- 帮助开发者提升后续代码质量
Integration with Code Quality Tools
与代码质量工具的集成
When to Use This Skill:
- During code review (before merge)
- In pull request comments
- Before creating new modules
- When refactoring legacy code
- To educate team members
- In design review meetings
Works Well With:
- Code review process
- Module spec generation
- Refactoring workflows
- Architecture discussions
- Mentoring and learning
何时使用本Skill:
- 代码审查期间(合并前)
- 拉取请求评论中
- 创建新模块前
- 重构遗留代码时
- 培训团队成员时
- 设计审查会议中
适配场景:
- 代码审查流程
- 模块规格生成
- 重构工作流
- 架构讨论
- 指导与学习
Resources
参考资源
- Philosophy:
~/.amplihack/.claude/context/PHILOSOPHY.md - Patterns:
~/.amplihack/.claude/context/PATTERNS.md - Brick Philosophy: See "Modular Architecture for AI" in PHILOSOPHY.md
- Zero-BS: See "Zero-BS Implementations" in PHILOSOPHY.md
- 哲学文档:
~/.amplihack/.claude/context/PHILOSOPHY.md - 模式文档:
~/.amplihack/.claude/context/PATTERNS.md - 积木式哲学:见PHILOSOPHY.md中的"AI模块化架构"
- 零冗余实现:见PHILOSOPHY.md中的"零冗余实现"
Remember
注意事项
This skill helps maintain code quality by:
- Catching issues before they become technical debt
- Educating developers on philosophy
- Keeping code simple and maintainable
- Preventing tightly-coupled systems
- Making code easier to understand and modify
Use it constructively - the goal is learning and improvement, not criticism.
本Skill通过以下方式维护代码质量:
- 在问题演变为技术债务前及时发现
- 向开发者传授哲学理念
- 保持代码简洁可维护
- 防止系统出现紧耦合
- 使代码更易于理解和修改
请建设性地使用本Skill——目标是学习和改进,而非批评。",