kaizen

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Kaizen: Continuous Improvement

Kaizen:持续改进

Apply continuous improvement mindset - suggest small iterative improvements, error-proof designs, follow established patterns, avoid over-engineering; automatically applied to guide quality and simplicity
应用持续改进思维——建议小步迭代式改进、防错设计、遵循既定模式、避免过度工程化;该方法会自动应用以保障代码质量与简洁性

Overview

概述

Small improvements, continuously. Error-proof by design. Follow what works. Build only what's needed.
Core principle: Many small improvements beat one big change. Prevent errors at design time, not with fixes.
持续进行微小改进。通过设计实现防错。遵循经实践验证的方案。只构建当前所需的功能。
核心原则: 大量微小改进的成效胜过一次重大变更。在设计阶段预防错误,而非事后修复。

When to Use

适用场景

Always applied for:
  • Code implementation and refactoring
  • Architecture and design decisions
  • Process and workflow improvements
  • Error handling and validation
Philosophy: Quality through incremental progress and prevention, not perfection through massive effort.
始终适用的场景:
  • 代码实现与重构
  • 架构与设计决策
  • 流程与工作流优化
  • 错误处理与验证
核心理念: 通过渐进式进展与预防措施保障质量,而非投入大量精力追求完美。

The Four Pillars

四大支柱

1. Continuous Improvement (Kaizen)

1. 持续改进(Kaizen)

Small, frequent improvements compound into major gains.
微小、频繁的改进会逐步积累为显著成果。

Principles

原则

Incremental over revolutionary:
  • Make smallest viable change that improves quality
  • One improvement at a time
  • Verify each change before next
  • Build momentum through small wins
Always leave code better:
  • Fix small issues as you encounter them
  • Refactor while you work (within scope)
  • Update outdated comments
  • Remove dead code when you see it
Iterative refinement:
  • First version: make it work
  • Second pass: make it clear
  • Third pass: make it efficient
  • Don't try all three at once
<Good> ```typescript // Iteration 1: Make it work const calculateTotal = (items: Item[]) => { let total = 0; for (let i = 0; i < items.length; i++) { total += items[i].price * items[i].quantity; } return total; };
// Iteration 2: Make it clear (refactor) const calculateTotal = (items: Item[]): number => { return items.reduce((total, item) => { return total + (item.price * item.quantity); }, 0); };
// Iteration 3: Make it robust (add validation) const calculateTotal = (items: Item[]): number => { if (!items?.length) return 0;
return items.reduce((total, item) => { if (item.price < 0 || item.quantity < 0) { throw new Error('Price and quantity must be non-negative'); } return total + (item.price * item.quantity); }, 0); };
Each step is complete, tested, and working
</Good>

<Bad>
```typescript
// Trying to do everything at once
const calculateTotal = (items: Item[]): number => {
  // Validate, optimize, add features, handle edge cases all together
  if (!items?.length) return 0;
  const validItems = items.filter(item => {
    if (item.price < 0) throw new Error('Negative price');
    if (item.quantity < 0) throw new Error('Negative quantity');
    return item.quantity > 0; // Also filtering zero quantities
  });
  // Plus caching, plus logging, plus currency conversion...
  return validItems.reduce(...); // Too many concerns at once
};
Overwhelming, error-prone, hard to verify </Bad>
渐进式优于革命性:
  • 做出能提升质量的最小可行变更
  • 一次只进行一项改进
  • 在进行下一项改进前验证当前变更的效果
  • 通过小胜积累动力
始终让代码变得更好:
  • 遇到小问题时立即修复
  • 在工作过程中进行重构(在范围内)
  • 更新过时的注释
  • 发现死代码时及时移除
迭代式优化:
  • 第一版:实现功能可用
  • 第二版:提升代码清晰度
  • 第三版:优化性能与健壮性
  • 不要试图同时完成这三步
<Good> ```typescript // Iteration 1: Make it work const calculateTotal = (items: Item[]) => { let total = 0; for (let i = 0; i < items.length; i++) { total += items[i].price * items[i].quantity; } return total; };
// Iteration 2: Make it clear (refactor) const calculateTotal = (items: Item[]): number => { return items.reduce((total, item) => { return total + (item.price * item.quantity); }, 0); };
// Iteration 3: Make it robust (add validation) const calculateTotal = (items: Item[]): number => { if (!items?.length) return 0;
return items.reduce((total, item) => { if (item.price < 0 || item.quantity < 0) { throw new Error('Price and quantity must be non-negative'); } return total + (item.price * item.quantity); }, 0); };
每个步骤都完整、经过测试且可正常运行
</Good>

<Bad>
```typescript
// Trying to do everything at once
const calculateTotal = (items: Item[]): number => {
  // Validate, optimize, add features, handle edge cases all together
  if (!items?.length) return 0;
  const validItems = items.filter(item => {
    if (item.price < 0) throw new Error('Negative price');
    if (item.quantity < 0) throw new Error('Negative quantity');
    return item.quantity > 0; // Also filtering zero quantities
  });
  // Plus caching, plus logging, plus currency conversion...
  return validItems.reduce(...); // Too many concerns at once
};
内容繁杂、容易出错、难以验证 </Bad>

In Practice

实践应用

When implementing features:
  1. Start with simplest version that works
  2. Add one improvement (error handling, validation, etc.)
  3. Test and verify
  4. Repeat if time permits
  5. Don't try to make it perfect immediately
When refactoring:
  • Fix one smell at a time
  • Commit after each improvement
  • Keep tests passing throughout
  • Stop when "good enough" (diminishing returns)
When reviewing code:
  • Suggest incremental improvements (not rewrites)
  • Prioritize: critical → important → nice-to-have
  • Focus on highest-impact changes first
  • Accept "better than before" even if not perfect
实现功能时:
  1. 从最简单的可用版本开始
  2. 添加一项改进(如错误处理、验证等)
  3. 测试并验证
  4. 若时间允许则重复上述步骤
  5. 不要试图立即做到完美
重构时:
  • 一次修复一个代码坏味道
  • 每次改进后提交代码
  • 全程保持测试通过
  • 当达到"足够好"时停止(收益递减时)
代码评审时:
  • 建议渐进式改进(而非重写)
  • 按优先级排序:关键→重要→锦上添花
  • 优先关注影响最大的变更
  • 接受"比之前更好"的结果,即便并非完美

2. Poka-Yoke (Error Proofing)

2. Poka-Yoke(防错设计)

Design systems that prevent errors at compile/design time, not runtime.
设计能在编译/设计阶段预防错误的系统,而非在运行时处理错误。

Principles

原则

Make errors impossible:
  • Type system catches mistakes
  • Compiler enforces contracts
  • Invalid states unrepresentable
  • Errors caught early (left of production)
Design for safety:
  • Fail fast and loudly
  • Provide helpful error messages
  • Make correct path obvious
  • Make incorrect path difficult
Defense in layers:
  1. Type system (compile time)
  2. Validation (runtime, early)
  3. Guards (preconditions)
  4. Error boundaries (graceful degradation)
让错误不可能发生:
  • 类型系统捕获错误
  • 编译器强制执行契约
  • 无法表示无效状态
  • 在生产前尽早发现错误
为安全性而设计:
  • 快速且明确地失败
  • 提供有帮助的错误信息
  • 让正确路径显而易见
  • 让错误路径难以执行
分层防御:
  1. 类型系统(编译时)
  2. 验证(运行时,早期)
  3. 守卫(前置条件)
  4. 错误边界(优雅降级)

Type System Error Proofing

类型系统防错

<Good> ```typescript // Error: string status can be any value type OrderBad = { status: string; // Can be "pending", "PENDING", "pnding", anything! total: number; };
// Good: Only valid states possible type OrderStatus = 'pending' | 'processing' | 'shipped' | 'delivered'; type Order = { status: OrderStatus; total: number; };
// Better: States with associated data type Order = | { status: 'pending'; createdAt: Date } | { status: 'processing'; startedAt: Date; estimatedCompletion: Date } | { status: 'shipped'; trackingNumber: string; shippedAt: Date } | { status: 'delivered'; deliveredAt: Date; signature: string };
// Now impossible to have shipped without trackingNumber
Type system prevents entire classes of errors
</Good>

<Good>
```typescript
// Make invalid states unrepresentable
type NonEmptyArray<T> = [T, ...T[]];

const firstItem = <T>(items: NonEmptyArray<T>): T => {
  return items[0]; // Always safe, never undefined!
};

// Caller must prove array is non-empty
const items: number[] = [1, 2, 3];
if (items.length > 0) {
  firstItem(items as NonEmptyArray<number>); // Safe
}
Function signature guarantees safety </Good>
<Good> ```typescript // Error: string status can be any value type OrderBad = { status: string; // Can be "pending", "PENDING", "pnding", anything! total: number; };
// Good: Only valid states possible type OrderStatus = 'pending' | 'processing' | 'shipped' | 'delivered'; type Order = { status: OrderStatus; total: number; };
// Better: States with associated data type Order = | { status: 'pending'; createdAt: Date } | { status: 'processing'; startedAt: Date; estimatedCompletion: Date } | { status: 'shipped'; trackingNumber: string; shippedAt: Date } | { status: 'delivered'; deliveredAt: Date; signature: string };
// Now impossible to have shipped without trackingNumber
类型系统可预防整类错误
</Good>

<Good>
```typescript
// Make invalid states unrepresentable
type NonEmptyArray<T> = [T, ...T[]];

const firstItem = <T>(items: NonEmptyArray<T>): T => {
  return items[0]; // Always safe, never undefined!
};

// Caller must prove array is non-empty
const items: number[] = [1, 2, 3];
if (items.length > 0) {
  firstItem(items as NonEmptyArray<number>); // Safe
}
函数签名可保障安全性 </Good>

Validation Error Proofing

验证防错

<Good> ```typescript // Error: Validation after use const processPayment = (amount: number) => { const fee = amount * 0.03; // Used before validation! if (amount <= 0) throw new Error('Invalid amount'); // ... };
// Good: Validate immediately const processPayment = (amount: number) => { if (amount <= 0) { throw new Error('Payment amount must be positive'); } if (amount > 10000) { throw new Error('Payment exceeds maximum allowed'); }
const fee = amount * 0.03; // ... now safe to use };
// Better: Validation at boundary with branded type type PositiveNumber = number & { readonly __brand: 'PositiveNumber' };
const validatePositive = (n: number): PositiveNumber => { if (n <= 0) throw new Error('Must be positive'); return n as PositiveNumber; };
const processPayment = (amount: PositiveNumber) => { // amount is guaranteed positive, no need to check const fee = amount * 0.03; };
// Validate at system boundary const handlePaymentRequest = (req: Request) => { const amount = validatePositive(req.body.amount); // Validate once processPayment(amount); // Use everywhere safely };
Validate once at boundary, safe everywhere else
</Good>
<Good> ```typescript // Error: Validation after use const processPayment = (amount: number) => { const fee = amount * 0.03; // Used before validation! if (amount <= 0) throw new Error('Invalid amount'); // ... };
// Good: Validate immediately const processPayment = (amount: number) => { if (amount <= 0) { throw new Error('Payment amount must be positive'); } if (amount > 10000) { throw new Error('Payment exceeds maximum allowed'); }
const fee = amount * 0.03; // ... now safe to use };
// Better: Validation at boundary with branded type type PositiveNumber = number & { readonly __brand: 'PositiveNumber' };
const validatePositive = (n: number): PositiveNumber => { if (n <= 0) throw new Error('Must be positive'); return n as PositiveNumber; };
const processPayment = (amount: PositiveNumber) => { // amount is guaranteed positive, no need to check const fee = amount * 0.03; };
// Validate at system boundary const handlePaymentRequest = (req: Request) => { const amount = validatePositive(req.body.amount); // Validate once processPayment(amount); // Use everywhere safely };
在边界处验证一次,之后可安全地在各处使用
</Good>

Guards and Preconditions

守卫与前置条件

<Good> ```typescript // Early returns prevent deeply nested code const processUser = (user: User | null) => { if (!user) { logger.error('User not found'); return; }
if (!user.email) { logger.error('User email missing'); return; }
if (!user.isActive) { logger.info('User inactive, skipping'); return; }
// Main logic here, guaranteed user is valid and active sendEmail(user.email, 'Welcome!'); };

Guards make assumptions explicit and enforced
</Good>
<Good> ```typescript // Early returns prevent deeply nested code const processUser = (user: User | null) => { if (!user) { logger.error('User not found'); return; }
if (!user.email) { logger.error('User email missing'); return; }
if (!user.isActive) { logger.info('User inactive, skipping'); return; }
// Main logic here, guaranteed user is valid and active sendEmail(user.email, 'Welcome!'); };

守卫让假设变得明确且可强制执行
</Good>

Configuration Error Proofing

配置防错

<Good> ```typescript // Error: Optional config with unsafe defaults type ConfigBad = { apiKey?: string; timeout?: number; };
const client = new APIClient({ timeout: 5000 }); // apiKey missing!
// Good: Required config, fails early type Config = { apiKey: string; timeout: number; };
const loadConfig = (): Config => { const apiKey = process.env.API_KEY; if (!apiKey) { throw new Error('API_KEY environment variable required'); }
return { apiKey, timeout: 5000, }; };
// App fails at startup if config invalid, not during request const config = loadConfig(); const client = new APIClient(config);
Fail at startup, not in production
</Good>
<Good> ```typescript // Error: Optional config with unsafe defaults type ConfigBad = { apiKey?: string; timeout?: number; };
const client = new APIClient({ timeout: 5000 }); // apiKey missing!
// Good: Required config, fails early type Config = { apiKey: string; timeout: number; };
const loadConfig = (): Config => { const apiKey = process.env.API_KEY; if (!apiKey) { throw new Error('API_KEY environment variable required'); }
return { apiKey, timeout: 5000, }; };
// App fails at startup if config invalid, not during request const config = loadConfig(); const client = new APIClient(config);
在启动时失败,而非在生产运行时
</Good>

In Practice

实践应用

When designing APIs:
  • Use types to constrain inputs
  • Make invalid states unrepresentable
  • Return Result<T, E> instead of throwing
  • Document preconditions in types
When handling errors:
  • Validate at system boundaries
  • Use guards for preconditions
  • Fail fast with clear messages
  • Log context for debugging
When configuring:
  • Required over optional with defaults
  • Validate all config at startup
  • Fail deployment if config invalid
  • Don't allow partial configurations
设计API时:
  • 使用类型约束输入
  • 让无效状态无法表示
  • 返回Result<T, E>而非抛出异常
  • 在类型中记录前置条件
处理错误时:
  • 在系统边界处进行验证
  • 使用守卫处理前置条件
  • 快速失败并提供清晰的信息
  • 记录调试所需的上下文
配置时:
  • 优先使用必填配置,而非带默认值的可选配置
  • 在启动时验证所有配置
  • 若配置无效则终止部署
  • 不允许部分配置

3. Standardized Work

3. 标准化工作

Follow established patterns. Document what works. Make good practices easy to follow.
遵循既定模式。记录有效的方案。让良好实践易于遵循。

Principles

原则

Consistency over cleverness:
  • Follow existing codebase patterns
  • Don't reinvent solved problems
  • New pattern only if significantly better
  • Team agreement on new patterns
Documentation lives with code:
  • README for setup and architecture
  • CLAUDE.md for AI coding conventions
  • Comments for "why", not "what"
  • Examples for complex patterns
Automate standards:
  • Linters enforce style
  • Type checks enforce contracts
  • Tests verify behavior
  • CI/CD enforces quality gates
一致性优于技巧性:
  • 遵循现有代码库的模式
  • 不要重新发明已解决的问题
  • 只有当新模式显著更优时才引入
  • 新模式需获得团队认可
文档与代码共存:
  • README用于说明设置与架构
  • CLAUDE.md用于AI编码规范
  • 注释用于说明"为什么",而非"是什么"
  • 为复杂模式提供示例
自动化标准执行:
  • 代码检查器(Linter)强制执行风格规范
  • 类型检查强制执行契约
  • 测试验证行为
  • CI/CD强制执行质量门限

Following Patterns

遵循模式

<Good> ```typescript // Existing codebase pattern for API clients class UserAPIClient { async getUser(id: string): Promise<User> { return this.fetch(`/users/${id}`); } }
// New code follows the same pattern class OrderAPIClient { async getOrder(id: string): Promise<Order> { return this.fetch(
/orders/${id}
); } }

Consistency makes codebase predictable
</Good>

<Bad>
```typescript
// Existing pattern uses classes
class UserAPIClient { /* ... */ }

// New code introduces different pattern without discussion
const getOrder = async (id: string): Promise<Order> => {
  // Breaking consistency "because I prefer functions"
};
Inconsistency creates confusion </Bad>
<Good> ```typescript // Existing codebase pattern for API clients class UserAPIClient { async getUser(id: string): Promise<User> { return this.fetch(`/users/${id}`); } }
// New code follows the same pattern class OrderAPIClient { async getOrder(id: string): Promise<Order> { return this.fetch(
/orders/${id}
); } }

一致性让代码库更具可预测性
</Good>

<Bad>
```typescript
// Existing pattern uses classes
class UserAPIClient { /* ... */ }

// New code introduces different pattern without discussion
const getOrder = async (id: string): Promise<Order> => {
  // Breaking consistency "because I prefer functions"
};
不一致会造成混淆 </Bad>

Error Handling Patterns

错误处理模式

<Good> ```typescript // Project standard: Result type for recoverable errors type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
// All services follow this pattern const fetchUser = async (id: string): Promise<Result<User, Error>> => { try { const user = await db.users.findById(id); if (!user) { return { ok: false, error: new Error('User not found') }; } return { ok: true, value: user }; } catch (err) { return { ok: false, error: err as Error }; } };
// Callers use consistent pattern const result = await fetchUser('123'); if (!result.ok) { logger.error('Failed to fetch user', result.error); return; } const user = result.value; // Type-safe!

Standard pattern across codebase
</Good>
<Good> ```typescript // Project standard: Result type for recoverable errors type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
// All services follow this pattern const fetchUser = async (id: string): Promise<Result<User, Error>> => { try { const user = await db.users.findById(id); if (!user) { return { ok: false, error: new Error('User not found') }; } return { ok: true, value: user }; } catch (err) { return { ok: false, error: err as Error }; } };
// Callers use consistent pattern const result = await fetchUser('123'); if (!result.ok) { logger.error('Failed to fetch user', result.error); return; } const user = result.value; // Type-safe!

代码库中使用标准模式
</Good>

Documentation Standards

文档标准

<Good> ```typescript /** * Retries an async operation with exponential backoff. * * Why: Network requests fail temporarily; retrying improves reliability * When to use: External API calls, database operations * When not to use: User input validation, internal function calls * * @example * const result = await retry( * () => fetch('https://api.example.com/data'), * { maxAttempts: 3, baseDelay: 1000 } * ); */ const retry = async <T>( operation: () => Promise<T>, options: RetryOptions ): Promise<T> => { // Implementation... }; ``` Documents why, when, and how </Good>
<Good> ```typescript /** * Retries an async operation with exponential backoff. * * Why: Network requests fail temporarily; retrying improves reliability * When to use: External API calls, database operations * When not to use: User input validation, internal function calls * * @example * const result = await retry( * () => fetch('https://api.example.com/data'), * { maxAttempts: 3, baseDelay: 1000 } * ); */ const retry = async <T>( operation: () => Promise<T>, options: RetryOptions ): Promise<T> => { // Implementation... }; ``` 记录了原因、适用场景与使用方法 </Good>

In Practice

实践应用

Before adding new patterns:
  • Search codebase for similar problems solved
  • Check CLAUDE.md for project conventions
  • Discuss with team if breaking from pattern
  • Update docs when introducing new pattern
When writing code:
  • Match existing file structure
  • Use same naming conventions
  • Follow same error handling approach
  • Import from same locations
When reviewing:
  • Check consistency with existing code
  • Point to examples in codebase
  • Suggest aligning with standards
  • Update CLAUDE.md if new standard emerges
添加新模式前:
  • 在代码库中搜索已解决的类似问题
  • 查看CLAUDE.md了解项目规范
  • 若要打破现有模式需与团队讨论
  • 引入新模式时更新文档
编写代码时:
  • 匹配现有文件结构
  • 使用相同的命名规范
  • 遵循相同的错误处理方式
  • 从相同位置导入模块
评审时:
  • 检查与现有代码的一致性
  • 指向代码库中的示例
  • 建议与标准对齐
  • 若出现新标准则更新CLAUDE.md

4. Just-In-Time (JIT)

4. 即时构建(JIT)

Build what's needed now. No more, no less. Avoid premature optimization and over-engineering.
只构建当前所需的内容。不多不少。避免过早优化与过度工程化。

Principles

原则

YAGNI (You Aren't Gonna Need It):
  • Implement only current requirements
  • No "just in case" features
  • No "we might need this later" code
  • Delete speculation
Simplest thing that works:
  • Start with straightforward solution
  • Add complexity only when needed
  • Refactor when requirements change
  • Don't anticipate future needs
Optimize when measured:
  • No premature optimization
  • Profile before optimizing
  • Measure impact of changes
  • Accept "good enough" performance
YAGNI(你不会需要它):
  • 仅实现当前需求
  • 不要添加"以防万一"的功能
  • 不要编写"以后可能需要"的代码
  • 删除投机性代码
最简单可行的方案:
  • 从直接的解决方案开始
  • 仅在需要时添加复杂度
  • 当需求变更时进行重构
  • 不要预测未来需求
基于度量进行优化:
  • 不要过早优化
  • 先分析再优化
  • 度量变更的影响
  • 接受"足够好"的性能

YAGNI in Action

YAGNI实践

<Good> ```typescript // Current requirement: Log errors to console const logError = (error: Error) => { console.error(error.message); }; ``` Simple, meets current need </Good> <Bad> ```typescript // Over-engineered for "future needs" interface LogTransport { write(level: LogLevel, message: string, meta?: LogMetadata): Promise<void>; }
class ConsoleTransport implements LogTransport { /... / } class FileTransport implements LogTransport { / ... / } class RemoteTransport implements LogTransport { / .../ }
class Logger { private transports: LogTransport[] = []; private queue: LogEntry[] = []; private rateLimiter: RateLimiter; private formatter: LogFormatter;
// 200 lines of code for "maybe we'll need it" }
const logError = (error: Error) => { Logger.getInstance().log('error', error.message); };
Building for imaginary future requirements
</Bad>

**When to add complexity:**
- Current requirement demands it
- Pain points identified through use
- Measured performance issues
- Multiple use cases emerged

<Good>
```typescript
// Start simple
const formatCurrency = (amount: number): string => {
  return `$${amount.toFixed(2)}`;
};

// Requirement evolves: support multiple currencies
const formatCurrency = (amount: number, currency: string): string => {
  const symbols = { USD: '$', EUR: '€', GBP: '£' };
  return `${symbols[currency]}${amount.toFixed(2)}`;
};

// Requirement evolves: support localization
const formatCurrency = (amount: number, locale: string): string => {
  return new Intl.NumberFormat(locale, {
    style: 'currency',
    currency: locale === 'en-US' ? 'USD' : 'EUR',
  }).format(amount);
};
Complexity added only when needed </Good>
<Good> ```typescript // Current requirement: Log errors to console const logError = (error: Error) => { console.error(error.message); }; ``` 简单,满足当前需求 </Good> <Bad> ```typescript // Over-engineered for "future needs" interface LogTransport { write(level: LogLevel, message: string, meta?: LogMetadata): Promise<void>; }
class ConsoleTransport implements LogTransport { /... / } class FileTransport implements LogTransport { / ... / } class RemoteTransport implements LogTransport { / .../ }
class Logger { private transports: LogTransport[] = []; private queue: LogEntry[] = []; private rateLimiter: RateLimiter; private formatter: LogFormatter;
// 200 lines of code for "maybe we'll need it" }
const logError = (error: Error) => { Logger.getInstance().log('error', error.message); };
为想象中的未来需求过度工程化
</Bad>

**何时添加复杂度:**
- 当前需求需要
- 通过使用发现痛点
- 度量到性能问题
- 出现多个用例

<Good>
```typescript
// Start simple
const formatCurrency = (amount: number): string => {
  return `$${amount.toFixed(2)}`;
};

// Requirement evolves: support multiple currencies
const formatCurrency = (amount: number, currency: string): string => {
  const symbols = { USD: '$', EUR: '€', GBP: '£' };
  return `${symbols[currency]}${amount.toFixed(2)}`;
};

// Requirement evolves: support localization
const formatCurrency = (amount: number, locale: string): string => {
  return new Intl.NumberFormat(locale, {
    style: 'currency',
    currency: locale === 'en-US' ? 'USD' : 'EUR',
  }).format(amount);
};
仅在需要时添加复杂度 </Good>

Premature Abstraction

过早抽象

<Bad> ```typescript // One use case, but building generic framework abstract class BaseCRUDService<T> { abstract getAll(): Promise<T[]>; abstract getById(id: string): Promise<T>; abstract create(data: Partial<T>): Promise<T>; abstract update(id: string, data: Partial<T>): Promise<T>; abstract delete(id: string): Promise<void>; }
class GenericRepository<T> { /300 lines / } class QueryBuilder<T> { / 200 lines/ } // ... building entire ORM for single table
Massive abstraction for uncertain future
</Bad>

<Good>
```typescript
// Simple functions for current needs
const getUsers = async (): Promise<User[]> => {
  return db.query('SELECT * FROM users');
};

const getUserById = async (id: string): Promise<User | null> => {
  return db.query('SELECT * FROM users WHERE id = $1', [id]);
};

// When pattern emerges across multiple entities, then abstract
Abstract only when pattern proven across 3+ cases </Good>
<Bad> ```typescript // One use case, but building generic framework abstract class BaseCRUDService<T> { abstract getAll(): Promise<T[]>; abstract getById(id: string): Promise<T>; abstract create(data: Partial<T>): Promise<T>; abstract update(id: string, data: Partial<T>): Promise<T>; abstract delete(id: string): Promise<void>; }
class GenericRepository<T> { /300 lines / } class QueryBuilder<T> { / 200 lines/ } // ... building entire ORM for single table
为不确定的未来进行大规模抽象
</Bad>

<Good>
```typescript
// Simple functions for current needs
const getUsers = async (): Promise<User[]> => {
  return db.query('SELECT * FROM users');
};

const getUserById = async (id: string): Promise<User | null> => {
  return db.query('SELECT * FROM users WHERE id = $1', [id]);
};

// When pattern emerges across multiple entities, then abstract
仅当模式在3个以上案例中得到验证时才进行抽象 </Good>

Performance Optimization

性能优化

<Good> ```typescript // Current: Simple approach const filterActiveUsers = (users: User[]): User[] => { return users.filter(user => user.isActive); };
// Benchmark shows: 50ms for 1000 users (acceptable) // ✓ Ship it, no optimization needed
// Later: After profiling shows this is bottleneck // Then optimize with indexed lookup or caching
Optimize based on measurement, not assumptions
</Good>

<Bad>
```typescript
// Premature optimization
const filterActiveUsers = (users: User[]): User[] => {
  // "This might be slow, so let's cache and index"
  const cache = new WeakMap();
  const indexed = buildBTreeIndex(users, 'isActive');
  // 100 lines of optimization code
  // Adds complexity, harder to maintain
  // No evidence it was needed
};
Complex solution for unmeasured problem </Bad>
<Good> ```typescript // Current: Simple approach const filterActiveUsers = (users: User[]): User[] => { return users.filter(user => user.isActive); };
// Benchmark shows: 50ms for 1000 users (acceptable) // ✓ Ship it, no optimization needed
// Later: After profiling shows this is bottleneck // Then optimize with indexed lookup or caching
基于度量进行优化,而非假设
</Good>

<Bad>
```typescript
// Premature optimization
const filterActiveUsers = (users: User[]): User[] => {
  // "This might be slow, so let's cache and index"
  const cache = new WeakMap();
  const indexed = buildBTreeIndex(users, 'isActive');
  // 100 lines of optimization code
  // Adds complexity, harder to maintain
  // No evidence it was needed
};
为未度量的问题提供复杂解决方案 </Bad>

In Practice

实践应用

When implementing:
  • Solve the immediate problem
  • Use straightforward approach
  • Resist "what if" thinking
  • Delete speculative code
When optimizing:
  • Profile first, optimize second
  • Measure before and after
  • Document why optimization needed
  • Keep simple version in tests
When abstracting:
  • Wait for 3+ similar cases (Rule of Three)
  • Make abstraction as simple as possible
  • Prefer duplication over wrong abstraction
  • Refactor when pattern clear
实现时:
  • 解决当前问题
  • 使用直接的方法
  • 抵制"假设"思维
  • 删除投机性代码
优化时:
  • 先分析,后优化
  • 度量优化前后的效果
  • 记录优化的原因
  • 在测试中保留简单版本
抽象时:
  • 等待3个以上相似案例(三次法则)
  • 让抽象尽可能简单
  • 宁愿重复也不要错误的抽象
  • 当模式清晰时进行重构

Integration with Commands

与命令的集成

The Kaizen skill guides how you work. The commands provide structured analysis:
  • /why
    : Root cause analysis (5 Whys)
  • /cause-and-effect
    : Multi-factor analysis (Fishbone)
  • /plan-do-check-act
    : Iterative improvement cycles
  • /analyse-problem
    : Comprehensive documentation (A3)
  • /analyse
    : Smart method selection (Gemba/VSM/Muda)
Use commands for structured problem-solving. Apply skill for day-to-day development.
Kaizen技能指导你的工作方式。命令提供结构化分析:
  • /why
    : 根本原因分析(5问法)
  • /cause-and-effect
    : 多因素分析(鱼骨图)
  • /plan-do-check-act
    : 迭代式改进周期
  • /analyse-problem
    : 全面文档记录(A3报告)
  • /analyse
    : 智能方法选择(现场观察/价值流图/浪费分析)
使用命令进行结构化问题解决。在日常开发中应用该技能。

Red Flags

危险信号

Violating Continuous Improvement:
  • "I'll refactor it later" (never happens)
  • Leaving code worse than you found it
  • Big bang rewrites instead of incremental
Violating Poka-Yoke:
  • "Users should just be careful"
  • Validation after use instead of before
  • Optional config with no validation
Violating Standardized Work:
  • "I prefer to do it my way"
  • Not checking existing patterns
  • Ignoring project conventions
Violating Just-In-Time:
  • "We might need this someday"
  • Building frameworks before using them
  • Optimizing without measuring
违反持续改进:
  • "我以后再重构"(通常不会发生)
  • 留下比你接手时更差的代码
  • 大爆炸式重写而非渐进式改进
违反Poka-Yoke:
  • "用户应该小心点"
  • 使用后才进行验证而非之前
  • 无验证的可选配置
违反标准化工作:
  • "我更喜欢按自己的方式做"
  • 不检查现有模式
  • 忽略项目规范
违反即时构建:
  • "我们某天可能会需要这个"
  • 在使用前构建框架
  • 未度量就进行优化

Remember

谨记

Kaizen is about:
  • Small improvements continuously
  • Preventing errors by design
  • Following proven patterns
  • Building only what's needed
Not about:
  • Perfection on first try
  • Massive refactoring projects
  • Clever abstractions
  • Premature optimization
Mindset: Good enough today, better tomorrow. Repeat.
Kaizen是关于:
  • 持续进行微小改进
  • 通过设计预防错误
  • 遵循经实践验证的模式
  • 只构建所需内容
不是关于:
  • 第一次就做到完美
  • 大规模重构项目
  • 巧妙的抽象
  • 过早优化
思维模式: 今天足够好,明天会更好。不断重复。