DRY:不要重复自己
每一条知识都应该有一个唯一、明确且权威的表达。
显示原始英文内容
DRY (Don't Repeat Yourself)
Every piece of knowledge must have a single, unambiguous, authoritative representation.
Takeaways
- The DRY principle is about avoiding duplication of knowledge in code. If the same idea or logic is in multiple places, it's a signal to refactor.
- When requirements change, you should update logic in only one place. Repeated code increases the risk of inconsistencies and bugs (you might fix a bug in one copy and forget about the others).
- Be careful to apply DRY wisely. It's about knowledge repetition, not just duplication. Sometimes two pieces of code look alike but do different jobs; merging them could over-complicate things.
Overview
The idea of DRY is simple: each fact or piece of logic in your system should be expressed once and only once. If you find the same code, formula, or rule in multiple modules, you're violating DRY. Such repetition creates hidden maintenance cost. When the business rule changes, you must hunt down every duplicate instance.
By following DRY, developers strive for a single, unique implementation of any given behavior. This often means abstracting common code into a function or class, or consolidating configuration into a single file.
DRY also applies to database schemas, tests, and documentation.
However, remember that DRY is about duplicated intent, not just similar-looking code. Two pieces of code can look identical but serve different purposes in an application.
Examples
An application has a database connection URL in five different source files. If the database host changes, you'd have to edit all five places. The DRY approach keeps that URL in a single configuration variable that all modules read.
If two parts of an app both format dates the same way, create a single formatDate() utility function and call it from both places. Now if the date format needs to change, there's precisely one function to modify.
Large codebases benefit from DRY through shared libraries. If multiple applications need the same security logic, create a shared library instead of copying code across applications.
Origins
The term "DRY" was coined in 1999 by Andy Hunt and Dave Thomas in their book The Pragmatic Programmer. They defined it as: "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."
Even earlier, avoiding code duplication was part of structured programming and the Unix philosophy. In Extreme Programming, a similar idea was known as "Once and Only Once." Hunt and Thomas gave it a catchy name and expanded its scope beyond just code to all information.
核心含义
DRY 关注的是知识重复,而不只是文本重复。如果同一业务规则散落在多个模块、配置和文档中,规则变化时就容易遗漏,系统会逐渐产生不一致。
消除重复前要确认它们确实表达同一知识。为了追求复用而强行抽象两个变化方向不同的模块,也会制造更难理解的耦合。
实践例子
订单金额校验同时出现在前端、后端和三个脚本里。应该明确哪个位置是权威规则,其他位置只负责展示、调用或做必要的防御性校验。
来源与边界
Andy Hunt 和 Dave Thomas 在《程序员修炼之道》中系统推广了 DRY。重复的代码有时是暂时的设计信号,先理解变化方向再抽象通常更安全。