design

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Design

设计

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
undefined

Get 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
undefined
cm deps . --format ai cm deps . --circular --format ai # Check for issues
undefined

Core Principles

核心原则

SOLID Principles

SOLID Principles

PrincipleDescriptionViolation Sign
Single ResponsibilityA class/module should have one reason to changeClass doing too many things
Open/ClosedOpen for extension, closed for modificationModifying existing code for new features
Liskov SubstitutionSubtypes must be substitutable for base typesOverridden methods breaking contracts
Interface SegregationMany specific interfaces > one general interfaceClients forced to depend on unused methods
Dependency InversionDepend on abstractions, not concretionsHigh-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 needed
Detect DRY violations with jscpd:
bash
undefined
DRY   - Don't Repeat Yourself: 提取通用逻辑,但避免过度抽象
KISS  - Keep It Simple, Stupid: 优先保证清晰而非精巧
YAGNI - You Aren't Gonna Need It: 不要提前构建不需要的功能
使用jscpd检测DRY原则违反情况:
bash
undefined

Find duplicate code blocks

Find duplicate code blocks

npx jscpd /path/to/source npx jscpd --pattern "src/**/*.ts"
undefined
npx jscpd /path/to/source npx jscpd --pattern "src/**/*.ts"
undefined

Simplicity 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: 测试设计与模式