solid-principles
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSOLID Principles Skill
SOLID 原则技能
Atomic skill for applying and validating SOLID principles
用于应用和验证SOLID原则的原子技能
Skill Definition
技能定义
yaml
skill_id: solid-principles
responsibility: Single - SOLID principle analysis and application
atomic: true
idempotent: trueyaml
skill_id: solid-principles
responsibility: Single - SOLID principle analysis and application
atomic: true
idempotent: trueParameter Schema
参数架构
typescript
interface SkillParams {
// Required
code: string; // Code to analyze
language: string; // Programming language
// Optional
principles?: ('SRP' | 'OCP' | 'LSP' | 'ISP' | 'DIP')[]; // Focus areas
strictness?: 'relaxed' | 'normal' | 'strict'; // Validation level
include_examples?: boolean; // Show fixes
}
interface SkillResult {
violations: Violation[];
compliance_score: number; // 0-100
suggestions: Suggestion[];
metrics: PrincipleMetrics;
}typescript
interface SkillParams {
// 必填项
code: string; // 待分析的代码
language: string; // 编程语言
// 可选项
principles?: ('SRP' | 'OCP' | 'LSP' | 'ISP' | 'DIP')[]; // 重点分析领域
strictness?: 'relaxed' | 'normal' | 'strict'; // 验证级别
include_examples?: boolean; // 是否显示修复示例
}
interface SkillResult {
violations: Violation[];
compliance_score: number; // 0-100
suggestions: Suggestion[];
metrics: PrincipleMetrics;
}Validation Rules
验证规则
yaml
input_validation:
code:
min_length: 10
max_length: 50000
required: true
language:
allowed: [typescript, javascript, python, java, csharp, go, ruby]
required: true
principles:
default: ['SRP', 'OCP', 'LSP', 'ISP', 'DIP']
output_validation:
compliance_score:
min: 0
max: 100
violations:
max_count: 50yaml
input_validation:
code:
min_length: 10
max_length: 50000
required: true
language:
allowed: [typescript, javascript, python, java, csharp, go, ruby]
required: true
principles:
default: ['SRP', 'OCP', 'LSP', 'ISP', 'DIP']
output_validation:
compliance_score:
min: 0
max: 100
violations:
max_count: 50Retry Logic
重试逻辑
yaml
retry_config:
max_attempts: 3
backoff:
type: exponential
initial_delay_ms: 1000
max_delay_ms: 10000
multiplier: 2
retryable_errors:
- TIMEOUT
- RATE_LIMIT
- CONTEXT_OVERFLOW
non_retryable_errors:
- INVALID_INPUT
- UNSUPPORTED_LANGUAGEyaml
retry_config:
max_attempts: 3
backoff:
type: exponential
initial_delay_ms: 1000
max_delay_ms: 10000
multiplier: 2
retryable_errors:
- TIMEOUT
- RATE_LIMIT
- CONTEXT_OVERFLOW
non_retryable_errors:
- INVALID_INPUT
- UNSUPPORTED_LANGUAGELogging & Observability
日志与可观测性
yaml
logging:
level: INFO
events:
- skill_invoked
- analysis_started
- violation_found
- analysis_completed
- error_occurred
metrics:
- name: analysis_duration_ms
type: histogram
- name: violations_per_principle
type: counter
- name: compliance_score
type: gauge
tracing:
span_name: solid_principles_analysis
attributes:
- language
- code_size
- principle_countyaml
logging:
level: INFO
events:
- skill_invoked
- analysis_started
- violation_found
- analysis_completed
- error_occurred
metrics:
- name: analysis_duration_ms
type: histogram
- name: violations_per_principle
type: counter
- name: compliance_score
type: gauge
tracing:
span_name: solid_principles_analysis
attributes:
- language
- code_size
- principle_countPrinciple Definitions
原则定义
SRP - Single Responsibility Principle
SRP - 单一职责原则
yaml
definition: "A class should have only one reason to change"
detection:
indicators:
- Multiple unrelated methods
- Mixed abstraction levels
- Too many dependencies
thresholds:
methods_per_class: 10
dependencies: 5
lines_of_code: 200yaml
definition: "一个类应该只有一个发生变化的原因"
detection:
indicators:
- 多个不相关的方法
- 混合的抽象级别
- 过多的依赖项
thresholds:
methods_per_class: 10
dependencies: 5
lines_of_code: 200OCP - Open/Closed Principle
OCP - 开闭原则
yaml
definition: "Open for extension, closed for modification"
detection:
indicators:
- Switch statements on type
- Instanceof/typeof checks
- Frequent modifications for new features
patterns:
- Strategy pattern opportunity
- Template method opportunityyaml
definition: "对扩展开放,对修改关闭"
detection:
indicators:
- 基于类型的switch语句
- Instanceof/typeof检查
- 为新增功能频繁修改代码
patterns:
- 策略模式适用场景
- 模板方法适用场景LSP - Liskov Substitution Principle
LSP - 里氏替换原则
yaml
definition: "Subtypes must be substitutable for base types"
detection:
indicators:
- Overridden methods with different behavior
- Empty method implementations
- Type checking in polymorphic code
violations:
- Precondition strengthening
- Postcondition weakening
- Invariant breakingyaml
definition: "子类型必须能够替换其基类型"
detection:
indicators:
- 重写方法的行为与父类不同
- 空方法实现
- 多态代码中的类型检查
violations:
- 前置条件增强
- 后置条件减弱
- 不变量破坏ISP - Interface Segregation Principle
ISP - 接口隔离原则
yaml
definition: "Clients should not depend on interfaces they don't use"
detection:
indicators:
- Large interfaces (>5 methods)
- Unused method implementations
- Throw NotImplemented patterns
thresholds:
max_interface_methods: 5yaml
definition: "客户端不应该依赖它不需要的接口"
detection:
indicators:
- 大型接口(超过5个方法)
- 未使用的方法实现
- 抛出NotImplemented的模式
thresholds:
max_interface_methods: 5DIP - Dependency Inversion Principle
DIP - 依赖倒置原则
yaml
definition: "Depend on abstractions, not concretions"
detection:
indicators:
- Direct instantiation with 'new'
- Concrete class parameters
- No interface/abstract usage
patterns:
- Constructor injection missing
- Service locator anti-patternyaml
definition: "依赖于抽象,而非具体实现"
detection:
indicators:
- 使用'new'直接实例化对象
- 具体类作为参数
- 未使用接口/抽象类
patterns:
- 缺少构造函数注入
- 服务定位器反模式Usage Examples
使用示例
Basic Analysis
基础分析
typescript
// Input
{
code: "class UserService { ... }",
language: "typescript"
}
// Output
{
violations: [
{
principle: "SRP",
location: "UserService:1",
severity: "high",
message: "Class has 5 different responsibilities",
suggestion: "Extract to: AuthService, ProfileService, NotificationService"
}
],
compliance_score: 65,
suggestions: [...],
metrics: { srp: 60, ocp: 80, lsp: 100, isp: 70, dip: 45 }
}typescript
// 输入
{
code: "class UserService { ... }",
language: "typescript"
}
// 输出
{
violations: [
{
principle: "SRP",
location: "UserService:1",
severity: "high",
message: "该类承担了5种不同职责",
suggestion: "拆分为:AuthService、ProfileService、NotificationService"
}
],
compliance_score: 65,
suggestions: [...],
metrics: { srp: 60, ocp: 80, lsp: 100, isp: 70, dip: 45 }
}Focused Analysis
聚焦分析
typescript
// Input
{
code: "interface Repository { ... }",
language: "typescript",
principles: ["ISP"],
strictness: "strict"
}typescript
// 输入
{
code: "interface Repository { ... }",
language: "typescript",
principles: ["ISP"],
strictness: "strict"
}Unit Test Template
单元测试模板
typescript
describe('SolidPrinciplesSkill', () => {
describe('analyze', () => {
it('should detect SRP violation in god class', async () => {
const code = `
class UserManager {
saveUser() {}
sendEmail() {}
generateReport() {}
validateInput() {}
logActivity() {}
}
`;
const result = await skill.analyze({ code, language: 'typescript' });
expect(result.violations).toContainEqual(
expect.objectContaining({ principle: 'SRP' })
);
expect(result.compliance_score).toBeLessThan(70);
});
it('should pass for well-designed code', async () => {
const code = `
class UserRepository {
save(user: User): void {}
find(id: string): User {}
delete(id: string): void {}
}
`;
const result = await skill.analyze({ code, language: 'typescript' });
expect(result.violations).toHaveLength(0);
expect(result.compliance_score).toBeGreaterThan(90);
});
it('should handle invalid input gracefully', async () => {
await expect(
skill.analyze({ code: '', language: 'typescript' })
).rejects.toThrow('INVALID_INPUT');
});
});
});typescript
describe('SolidPrinciplesSkill', () => {
describe('analyze', () => {
it('should detect SRP violation in god class', async () => {
const code = `
class UserManager {
saveUser() {}
sendEmail() {}
generateReport() {}
validateInput() {}
logActivity() {}
}
`;
const result = await skill.analyze({ code, language: 'typescript' });
expect(result.violations).toContainEqual(
expect.objectContaining({ principle: 'SRP' })
);
expect(result.compliance_score).toBeLessThan(70);
});
it('should pass for well-designed code', async () => {
const code = `
class UserRepository {
save(user: User): void {}
find(id: string): User {}
delete(id: string): void {}
}
`;
const result = await skill.analyze({ code, language: 'typescript' });
expect(result.violations).toHaveLength(0);
expect(result.compliance_score).toBeGreaterThan(90);
});
it('should handle invalid input gracefully', async () => {
await expect(
skill.analyze({ code: '', language: 'typescript' })
).rejects.toThrow('INVALID_INPUT');
});
});
});Error Handling
错误处理
yaml
errors:
INVALID_INPUT:
code: 400
message: "Invalid input parameters"
recovery: "Check parameter schema"
UNSUPPORTED_LANGUAGE:
code: 400
message: "Language not supported"
recovery: "Use supported language"
ANALYSIS_TIMEOUT:
code: 408
message: "Analysis exceeded time limit"
recovery: "Reduce code size or complexity"
CONTEXT_OVERFLOW:
code: 413
message: "Code too large for analysis"
recovery: "Split into smaller modules"yaml
errors:
INVALID_INPUT:
code: 400
message: "输入参数无效"
recovery: "检查参数架构"
UNSUPPORTED_LANGUAGE:
code: 400
message: "不支持该编程语言"
recovery: "使用支持的编程语言"
ANALYSIS_TIMEOUT:
code: 408
message: "分析超出时间限制"
recovery: "减小代码规模或复杂度"
CONTEXT_OVERFLOW:
code: 413
message: "代码过大,无法进行分析"
recovery: "拆分为更小的模块"Integration
集成
yaml
requires:
- code_parser
- ast_analyzer
emits:
- solid_analysis_completed
- violation_detected
consumed_by:
- 01-design-principles (bonded agent)
- 04-refactoring (for smell detection)yaml
requires:
- code_parser
- ast_analyzer
emits:
- solid_analysis_completed
- violation_detected
consumed_by:
- 01-design-principles (bonded agent)
- 04-refactoring (for smell detection)