design
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDesign
设计
Guidelines for requirements analysis, design principles, architecture, and security.
需求分析、设计原则、架构与安全相关指南。
Requirements Analysis
需求分析
Before Writing Code
编码前
- Understand the requirements
- Consider edge cases
- Plan the approach
- Think about testing
- 理解需求
- 考虑边界情况
- 规划实现方案
- 考虑测试方案
Tools for Understanding Existing Code
现有代码理解工具
Before designing new features, understand the existing codebase:
bash
undefined在设计新功能前,先理解现有代码库:
bash
undefinedGet project overview with codemapper
Get project overview with codemapper
cm stats . --format ai
cm map . --level 2 --format ai
cm stats . --format ai
cm map . --level 2 --format ai
Find entry points and main flows
Find entry points and main flows
cm query main . --format ai
cm callees main . --format ai
cm query main . --format ai
cm callees main . --format ai
Understand module dependencies
Understand module dependencies
cm deps . --format ai
cm deps . --circular --format ai # Check for issues
undefinedcm deps . --format ai
cm deps . --circular --format ai # Check for issues
undefinedCore Principles
核心原则
SOLID Principles
SOLID Principles
| Principle | Description | Violation Sign |
|---|---|---|
| Single Responsibility | A class/module should have one reason to change | Class doing too many things |
| Open/Closed | Open for extension, closed for modification | Modifying existing code for new features |
| Liskov Substitution | Subtypes must be substitutable for base types | Overridden methods breaking contracts |
| Interface Segregation | Many specific interfaces > one general interface | Clients forced to depend on unused methods |
| Dependency Inversion | Depend on abstractions, not concretions | High-level modules importing low-level details |
| 原则 | 描述 | 违反迹象 |
|---|---|---|
| Single Responsibility | 一个类/模块应该只有一个变更理由 | 一个类承担过多职责 |
| Open/Closed | 对扩展开放,对修改关闭 | 为新增功能修改现有代码 |
| Liskov Substitution | 子类必须能够替换基类使用 | 重写方法破坏原有契约 |
| Interface Segregation | 多个专用接口优于一个通用接口 | 客户端被迫依赖未使用的方法 |
| Dependency Inversion | 依赖抽象而非具体实现 | 高层模块导入底层实现细节 |
DRY, KISS, YAGNI
DRY, KISS, YAGNI
DRY - Don't Repeat Yourself: Extract common logic, but don't over-abstract
KISS - Keep It Simple, Stupid: Prefer clarity over cleverness
YAGNI - You Aren't Gonna Need It: Don't build features until neededDetect DRY violations with jscpd:
bash
undefinedDRY - Don't Repeat Yourself: 提取通用逻辑,但避免过度抽象
KISS - Keep It Simple, Stupid: 优先保证清晰而非精巧
YAGNI - You Aren't Gonna Need It: 不要提前构建不需要的功能使用jscpd检测DRY原则违反情况:
bash
undefinedFind duplicate code blocks
Find duplicate code blocks
npx jscpd /path/to/source
npx jscpd --pattern "src/**/*.ts"
undefinednpx jscpd /path/to/source
npx jscpd --pattern "src/**/*.ts"
undefinedSimplicity Over Complexity
简洁优先于复杂
Simple, working code beats clever, complex code.
❌ OVERENGINEERed ✅ SIMPLE
─────────────────────────────────────────────────────
AbstractFactoryProvider Direct instantiation
5 layers of indirection 1-2 layers max
Generic solution for 1 use case Specific solution that works
"Future-proof" architecture Solve today's problem
Premature optimization Optimize when needed简洁、可运行的代码优于花哨、复杂的代码。
❌ 过度设计 ✅ 简洁设计
─────────────────────────────────────────────────────
AbstractFactoryProvider 直接实例化
5层间接调用 最多1-2层
为单一场景设计通用方案 针对场景的专用可行方案
"面向未来"的架构 解决当前问题
过早优化 需要时再优化Security by Design
设计安全
Threat Modeling
威胁建模
- Identify threat vectors
- Plan for input validation
- Consider authentication/authorization
- Plan for data protection
- Plan for logging and monitoring
- Plan for audit trails
- 识别威胁载体
- 规划输入验证
- 考虑身份认证与授权
- 规划数据保护
- 规划日志与监控
- 规划审计追踪
Input Validation
输入验证
typescript
// ✅ GOOD: Validate all inputs
interface CreateUserInput {
name: string;
email: string;
age?: number;
}
function createUser(input: CreateUserInput): User {
if (!input.name || input.name.length < 2) {
throw new ValidationError("Name must be at least 2 characters");
}
if (!isValidEmail(input.email)) {
throw new ValidationError("Invalid email format");
}
if (input.age !== undefined && (input.age < 0 || input.age > 120)) {
throw new ValidationError("Age must be between 0 and 120");
}
// Proceed with valid input
}typescript
// ✅ GOOD: Validate all inputs
interface CreateUserInput {
name: string;
email: string;
age?: number;
}
function createUser(input: CreateUserInput): User {
if (!input.name || input.name.length < 2) {
throw new ValidationError("Name must be at least 2 characters");
}
if (!isValidEmail(input.email)) {
throw new ValidationError("Invalid email format");
}
if (input.age !== undefined && (input.age < 0 || input.age > 120)) {
throw new ValidationError("Age must be between 0 and 120");
}
// Proceed with valid input
}Authentication & Authorization
身份认证与授权
typescript
// ✅ GOOD: Proper auth and authorization
interface AuthenticatedRequest {
userId: string;
role: "admin" | "user" | "guest";
}
function deleteUser(request: AuthenticatedRequest, userId: string) {
if (request.role !== "admin") {
throw new ForbiddenError("Only admins can delete users");
}
if (userId === request.userId) {
throw new BadRequestError("Cannot delete yourself");
}
// Proceed with authorized operation
}typescript
// ✅ GOOD: Proper auth and authorization
interface AuthenticatedRequest {
userId: string;
role: "admin" | "user" | "guest";
}
function deleteUser(request: AuthenticatedRequest, userId: string) {
if (request.role !== "admin") {
throw new ForbiddenError("Only admins can delete users");
}
if (userId === request.userId) {
throw new BadRequestError("Cannot delete yourself");
}
// Proceed with authorized operation
}Related Skills
相关技能
- implementation: Code quality guidelines
- review: Code review checklist
- maintenance: Refactoring and technical debt
- typescript: Type safety and interfaces
- vitest: Test design and patterns
- implementation: 代码质量指南
- review: 代码审查清单
- maintenance: 重构与技术债务
- typescript: 类型安全与接口
- vitest: 测试设计与模式