DRY原则 logo

DRY原则

Organization
microwind
DRY原则

Don't Repeat Yourself - 系统中每一个知识点都应该有唯一、权威的表示,避免重复代码和重复逻辑。

Overview

Publishermicrowind
Repositoryai-skills
Skill nameDRY原则
Stars
93
Forks
25
Bundled files
2
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 2 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by microwind on GitHub. Read the source before you install it.

Installation

Install the DRY原则 AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/microwind/ai-skills/tree/main/design-principles/dry-principle
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/microwind/ai-skills.git /tmp/ai-skills
mkdir -p .claude/skills
cp -r /tmp/ai-skills/design-principles/dry-principle .claude/skills/microwind-dry
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable DRY原则 in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads DRY原则 on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so DRY原则 is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

DRY 原则 (Don't Repeat Yourself)

概述

DRY 原则由 Andy Hunt 和 Dave Thomas 在《程序员修炼之道》中提出:系统中每一个知识点都应该有唯一、明确、权威的表示。

核心思想:

  • 不是仅仅指"不要复制粘贴代码"
  • 更深层含义是避免知识的重复(业务规则、逻辑、数据定义)
  • 修改一个业务规则时,只需要改一个地方

重复的三种类型:

  • 代码重复:相同的代码段出现多次
  • 逻辑重复:代码不同但做相同的事
  • 知识重复:同一业务规则在多处定义

代码重复示例

java
// ❌ 代码重复
public class OrderService {
    public double calculateTotal(Order order) {
        double total = 0;
        for (Item item : order.getItems()) {
            total += item.getPrice() * item.getQuantity();
        }
        if (total > 1000) total *= 0.9;  // 折扣逻辑
        total *= 1.13;  // 税率
        return total;
    }

    public double calculateQuote(List<Item> items) {
        double total = 0;
        for (Item item : items) {
            total += item.getPrice() * item.getQuantity();  // 重复!
        }
        if (total > 1000) total *= 0.9;  // 重复!
        total *= 1.13;  // 重复!
        return total;
    }
}

// ✅ 消除重复
public class PricingService {
    private static final double DISCOUNT_THRESHOLD = 1000;
    private static final double DISCOUNT_RATE = 0.9;
    private static final double TAX_RATE = 1.13;

    public double calculateSubtotal(List<Item> items) {
        return items.stream()
            .mapToDouble(i -> i.getPrice() * i.getQuantity())
            .sum();
    }

    public double applyDiscountAndTax(double subtotal) {
        double discounted = subtotal > DISCOUNT_THRESHOLD
            ? subtotal * DISCOUNT_RATE : subtotal;
        return discounted * TAX_RATE;
    }

    public double calculateTotal(List<Item> items) {
        return applyDiscountAndTax(calculateSubtotal(items));
    }
}

逻辑重复示例

python
# ❌ 代码不同,但逻辑重复(都在验证邮箱)
class UserRegistration:
    def register(self, email: str):
        if "@" not in email or "." not in email.split("@")[1]:
            raise ValueError("无效邮箱")

class Newsletter:
    def subscribe(self, email: str):
        import re
        if not re.match(r'^[\w.]+@[\w.]+\.\w+$', email):
            raise ValueError("邮箱格式错误")

# ✅ 统一验证逻辑
class EmailValidator:
    @staticmethod
    def validate(email: str) -> bool:
        import re
        return bool(re.match(r'^[\w.]+@[\w.]+\.\w+$', email))

class UserRegistration:
    def register(self, email: str):
        if not EmailValidator.validate(email):
            raise ValueError("无效邮箱")

class Newsletter:
    def subscribe(self, email: str):
        if not EmailValidator.validate(email):
            raise ValueError("无效邮箱")

知识重复示例

typescript
// ❌ 同一业务规则在多处定义
// config.ts
const MAX_LOGIN_ATTEMPTS = 5;

// auth.service.ts
if (attempts > 5) {  // 硬编码,与 config 不同步
    lockAccount();
}

// auth.test.ts
expect(lockAfterAttempts).toBe(5);  // 测试中又写了一遍

// ✅ 单一来源
// config.ts
export const AUTH_CONFIG = {
    MAX_LOGIN_ATTEMPTS: 5,
} as const;

// auth.service.ts
import { AUTH_CONFIG } from './config';
if (attempts > AUTH_CONFIG.MAX_LOGIN_ATTEMPTS) {
    lockAccount();
}

何时重复是可以接受的

1. 偶然重复:两段代码现在相同但变化原因不同
   - 订单折扣和会员折扣恰好都是 9 折
   - 未来可能独立变化,强行合并反而有害

2. 跨服务重复:微服务间的 DTO
   - 不同服务可能独立演进
   - 共享库引入更大的耦合问题

3. 测试代码:测试中的重复有时提高可读性
   - 每个测试方法自包含,比抽象更清晰

优缺点分析

✅ 优点

  1. 一处修改,全局生效 - 减少遗漏
  2. 代码量减少 - 更易维护
  3. 一致性保证 - 业务规则不会自相矛盾
  4. bug 修复只需一次 - 不会修了一处忘了另一处

❌ 过度 DRY 的危害

  1. 错误的抽象 - 把偶然相似的代码强行合并
  2. 增加耦合 - 不相关的模块共享代码
  3. 降低可读性 - 过度间接让代码难以追踪
  4. 过早抽象 - 只出现两次就抽取,可能方向错误

最佳实践

Rule of Three(三次法则)

第1次:直接写
第2次:允许重复,标注 TODO
第3次:重构,提取共同逻辑

不要在重复出现2次时就抽象——你可能还不了解正确的抽象方向

消除重复的方法

重复类型消除方法示例
代码片段重复提取方法extractMethod()
类间重复提取基类/工具类BaseService, Utils
配置重复集中配置config.yaml
数据定义重复代码生成OpenAPI → DTO
文档重复从代码生成文档JavaDoc

与其他原则的关系

原则关系
SRPSRP 拆分职责,DRY 合并重复知识
KISSDRY 有时与 KISS 冲突,过度 DRY 增加复杂性
YAGNI不要为了未来可能的 DRY 而提前抽象

总结

DRY 核心:每个知识点只有一个权威表示。

实践要点:

  • 区分代码重复、逻辑重复、知识重复
  • 遵循三次法则,不要过早抽象
  • 接受偶然重复和跨边界重复
  • DRY 的反面不是 WET,而是错误的抽象

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the DRY原则 AI skill do?

Don't Repeat Yourself - 系统中每一个知识点都应该有唯一、权威的表示,避免重复代码和重复逻辑。

Why use DRY原则 on TypingMind?

Because you install it once and use it with any model. DRY原则 is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install DRY原则 in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/microwind/ai-skills/tree/main/design-principles/dry-principle. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use DRY原则?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with DRY原则?

As many as you like. As long as a model supports skills, you can use DRY原则 with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the DRY原则 AI skill free?

Yes. It is published on GitHub by microwind under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇