Software Design Principles 标志

Software Design Principles

社区
NTCoding
software-design-principles

Object-oriented design principles including object calisthenics, dependency inversion, fail-fast error handling, feature envy detection, and intention-revealing naming. Triggers on: writing new classes or functions, refactoring, code review, 'clean up', method longer than 10 lines, feature envy, primitive obsession, deep nesting.

概览

发布者NTCoding
代码仓库claude-skillz
技能名称software-design-principles
星标数
356
复刻数
47
附带文件
仅含指令
链接
  • Markdown 格式的指令

    模型按需加载的 SKILL.md 文件,因此只有在请求确实匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 NTCoding 发布于 GitHub。请在安装前查看源内容。

安装

在 TypingMind 中安装 Software Design Principles AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/NTCoding/claude-skillz/tree/main/software-design-principles
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/NTCoding/claude-skillz.git /tmp/claude-skillz
mkdir -p .claude/skills
cp -r /tmp/claude-skillz/software-design-principles .claude/skills/software-design-principles
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Software Design Principles,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Software Design Principles。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Software Design Principles 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会获取指令,因此未使用的技能不会产生额外费用。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Software Design Principles

Professional software design patterns and principles for writing maintainable, well-structured code.

Critical Rules

🚨 Fail-fast over silent fallbacks. Never use fallback chains (value ?? backup ?? 'unknown'). If data should exist, validate and throw a clear error.

🚨 Strive for maximum type-safety. No any. No as. Type escape hatches defeat TypeScript's purpose. There's always a type-safe solution.

🚨 Make illegal states unrepresentable. Use discriminated unions, not optional fields. If a state combination shouldn't exist, make the type system forbid it.

🚨 Inject dependencies, don't instantiate. No new SomeService() inside methods. Pass dependencies through constructors.

🚨 Intention-revealing names only. Never use data, utils, helpers, handler, processor. Name things for what they do in the domain.

🚨 No code comments. Comments are a failure to express intent in code. If you need a comment to explain what code does, the code isn't clear enough—refactor it.

🚨 Use Zod for runtime validation. In TypeScript, use Zod schemas for parsing external data, API responses, and user input. Type inference from schemas keeps types and validation in sync.

When This Applies

  • Writing new code (these are defaults, not just refactoring goals)
  • Refactoring existing code
  • Code reviews and design reviews
  • During TDD REFACTOR phase
  • When analyzing coupling and cohesion

Core Philosophy

Well-designed, maintainable code is far more important than getting things done quickly. Every design decision should favor:

  • Clarity over cleverness
  • Explicit over implicit
  • Fail-fast over silent fallbacks
  • Loose coupling over tight integration
  • Intention-revealing over generic

Code Without Comments

Never write comments - write expressive code instead.

Object Calisthenics

Apply object calisthenics principles:

The Nine Rules

  1. One level of indentation per method

    • In practice, I will tolerate upto 3
  2. Don't use the ELSE keyword

    • Use early returns instead
  3. Wrap all primitives and strings

    • Create value objects
    • Encapsulate validation logic
    • Make domain concepts explicit
  4. First class collections

    • Classes with collections should contain nothing else
  5. One dot per line

  6. Don't abbreviate

    • Use full, descriptive names
  7. Keep all entities small

    • Small classes (< 150 lines)
    • Small methods (< 10 lines)
    • Small packages/modules
    • Easier to understand and maintain
  8. Avoid getters/setters/properties on entities

    • Tell, don't ask
    • Objects should do work, not expose data

When to Apply

  • During refactoring:

  • During code review:

Feature Envy Detection

Method uses another class's data more than its own? Move it there.

typescript
// ❌ FEATURE ENVY - obsessed with Order's data
class InvoiceGenerator {
  generate(order: Order): Invoice {
    const total = order.getItems().map(i => i.getPrice() * i.getQuantity()).reduce((a,b) => a+b, 0)
    return new Invoice(total + total * order.getTaxRate() + order.calculateShipping())
  }
}

// ✅ Move logic to the class it envies
class Order {
  calculateTotal(): number { /* uses this.items, this.taxRate */ }
}
class InvoiceGenerator {
  generate(order: Order): Invoice { return new Invoice(order.calculateTotal()) }
}

Detection: Count external vs own references. More external? Feature envy.

Dependency Inversion Principle

Don't instantiate dependencies inside methods. Inject them.

typescript
// ❌ TIGHT COUPLING
class OrderProcessor {
  process(order: Order): void {
    const validator = new OrderValidator()  // Hard to test/change
    const emailer = new EmailService()      // Hidden dependency
  }
}

// ✅ LOOSE COUPLING
class OrderProcessor {
  constructor(private validator: OrderValidator, private emailer: EmailService) {}
  process(order: Order): void {
    this.validator.isValid(order)  // Injected, mockable
    this.emailer.send(...)         // Explicit dependency
  }
}

Scan for: new X() inside methods, static method calls. Extract to constructor.

Fail-Fast Error Handling

NEVER use fallback chains:

typescript
value ?? backup ?? default ?? 'unknown'  // ❌

Validate and throw clear errors instead:

typescript
// ❌ SILENT FAILURE - hides problems
return content.eventType ?? content.className ?? 'Unknown'

// ✅ FAIL FAST - immediate, debuggable
if (!content.eventType) {
  throw new Error(`Expected 'eventType', got undefined. Keys: [${Object.keys(content)}]`)
}
return content.eventType

Error format: Expected [X]. Got [Y]. Context: [debugging info]

Naming Conventions

Principle: Use business domain terminology and intention-revealing names. Never use generic programmer jargon.

Forbidden Generic Names

NEVER use these names:

  • data
  • utils
  • helpers
  • common
  • shared
  • manager
  • handler
  • processor

These names are meaningless - they tell you nothing about what the code actually does.

Intention-Revealing Names

Instead of generic names, use specific domain language:

typescript
// ❌ GENERIC - meaningless
class DataProcessor {
  processData(data: any): any {
    const utils = new DataUtils()
    return utils.transform(data)
  }
}

// ✓ INTENTION-REVEALING - clear purpose
class OrderTotalCalculator {
  calculateTotal(order: Order): Money {
    return taxCalculator.applyTax(order.subtotal, order.taxRate)
  }
}

Naming Checklist

For classes:

  • Does the name reveal what the class is responsible for?
  • Is it a noun (or noun phrase) from the domain?
  • Would a domain expert recognize this term?

For methods:

  • Does the name reveal what the method does?
  • Is it a verb (or verb phrase)?
  • Does it describe the business operation?

For variables:

  • Does the name reveal what the variable contains?
  • Is it specific to this context?
  • Could someone understand it without reading the code?

Refactoring Generic Names

When you encounter generic names:

  1. Understand the purpose: What is this really doing?
  2. Ask domain experts: What would they call this?
  3. Extract domain concept: Is there a domain term for this?
  4. Rename comprehensively: Update all references

Type-Driven Design

Principle: Follow Scott Wlaschin's type-driven approach to domain modeling. Express domain concepts using the type system.

Make Illegal States Unrepresentable

Use types to encode business rules:

typescript
// ❌ PRIMITIVE OBSESSION - illegal states possible
interface Order {
  status: string  // Could be any string
  shippedDate: Date | null  // Could be set when status != 'shipped'
}

// ✓ TYPE-SAFE - illegal states impossible
type UnconfirmedOrder = { type: 'unconfirmed', items: Item[] }
type ConfirmedOrder = { type: 'confirmed', items: Item[], confirmationNumber: string }
type ShippedOrder = { type: 'shipped', items: Item[], confirmationNumber: string, shippedDate: Date }

type Order = UnconfirmedOrder | ConfirmedOrder | ShippedOrder

Avoid Type Escape Hatches

STRICTLY FORBIDDEN without explicit user approval:

  • any type
  • as type assertions (as unknown as, as any, as SomeType)
  • @ts-ignore / @ts-expect-error

There is always a better type-safe solution. These make code unsafe and defeat TypeScript's purpose.

Use the Type System for Validation

typescript
// ✓ TYPE-SAFE - validates at compile time
type PositiveNumber = number & { __brand: 'positive' }

function createPositive(value: number): PositiveNumber {
  if (value <= 0) {
    throw new Error(`Expected positive number, got ${value}`)
  }
  return value as PositiveNumber
}

// Can only be called with validated positive numbers
function calculateDiscount(price: PositiveNumber, rate: number): Money {
  // price is guaranteed positive by type system
}

Prefer Immutability

Principle: Default to immutable data. Mutation is a source of bugs—unexpected changes, race conditions, and difficult debugging.

The Problem: Mutable State

typescript
// MUTABLE - hard to reason about
function processOrder(order: Order): void {
  order.status = 'processing'  // Mutates input!
  order.items.push(freeGift)   // Side effect!
}

// Caller has no idea their object changed
const myOrder = getOrder()
processOrder(myOrder)
// myOrder is now different - surprise!

The Solution: Return New Values

typescript
// IMMUTABLE - predictable
function processOrder(order: Order): Order {
  return {
    ...order,
    status: 'processing',
    items: [...order.items, freeGift]
  }
}

// Caller controls what happens
const myOrder = getOrder()
const processedOrder = processOrder(myOrder)
// myOrder unchanged, processedOrder is new

Application Rules

  • Prefer const over let
  • Prefer spread (...) over mutation
  • Prefer map/filter/reduce over forEach with mutation
  • If you must mutate, make it explicit and contained

YAGNI - You Aren't Gonna Need It

Principle: Don't build features until they're actually needed. Speculative code is waste—it costs time to write, time to maintain, and is often wrong when requirements become clear.

The Problem: Speculative Generalization

typescript
// YAGNI VIOLATION - over-engineered for "future" needs
interface PaymentProcessor {
  process(payment: Payment): Result
  refund(payment: Payment): Result
  partialRefund(payment: Payment, amount: Money): Result
  schedulePayment(payment: Payment, date: Date): Result
  recurringPayment(payment: Payment, schedule: Schedule): Result
  // ... 10 more methods "we might need"
}

// Only ONE method is actually used today

Application Rules

  • Build the simplest thing that works
  • Add capabilities when requirements demand them, not before
  • "But we might need it" is not a requirement

When Tempted to Cut Corners

STOP if you're about to:

  • Use ?? chains → fail fast with clear error instead
  • Use any or as → fix the types, not the symptoms
  • Use new X() inside a method → inject through constructor
  • Name something data, utils, handler → use domain language
  • Add a getter → ask if the object should do the work instead
  • Skip refactor because "it works" → refactor IS part of the work
  • Write a comment → make the code self-explanatory
  • Mutate a parameter → return a new value
  • Build "for later" → build what you need now

常见问题

Software Design Principles AI 技能有什么作用?

Object-oriented design principles including object calisthenics, dependency inversion, fail-fast error handling, feature envy detection, and intention-revealing naming. Triggers on: writing new classes or functions, refactoring, code review, 'clean up', method longer than 10 lines, feature envy, primitive obsession, deep nesting.

为什么在 TypingMind 中使用 Software Design Principles?

因为您只需安装一次,就能搭配任何模型使用。Software Design Principles 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型,甚至可以在聊天中途切换模型,而不会影响技能正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Software Design Principles?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/NTCoding/claude-skillz/tree/main/software-design-principles。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Software Design Principles?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Software Design Principles 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以搭配 Software Design Principles 使用,包括 GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等,都可在 TypingMind 中使用您自己的 API 密钥接入。

Software Design Principles AI 技能免费吗?

该技能源自 NTCoding 在 GitHub 上发布的项目。请查看代码仓库了解许可条款。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇