Logo Software Design Principles

Software Design Principles

Cộng đồng
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.

Tổng quan

Nhà phát hànhNTCoding
Kho mãclaude-skillz
Tên kỹ năngsoftware-design-principles
Sao
356
Bản fork
47
Tệp đi kèm
Chỉ có hướng dẫn
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được NTCoding công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Software Design Principles trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/NTCoding/claude-skillz/tree/main/software-design-principles
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

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
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Software Design Principles trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Software Design Principles ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Software Design Principles không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

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

Câu hỏi thường gặp

Kỹ năng AI Software Design Principles làm được gì?

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.

Vì sao nên dùng Software Design Principles trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Software Design Principles là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Software Design Principles trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/NTCoding/claude-skillz/tree/main/software-design-principles. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Software Design Principles?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Software Design Principles với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Software Design Principles với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Software Design Principles có miễn phí không?

Kỹ năng này được NTCoding phát hành trên GitHub. Hãy xem điều khoản giấy phép trong kho mã. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇