DRY principle

Also known as: DRY · Don't repeat yourself

On this page 6

The DRY principle, short for Don’t repeat yourself, is a software design guideline stating that every piece of knowledge must have a single, unambiguous, authoritative representation within a system. In software architecture and everyday programming, it aims to ensure that a change to a business rule, data format or configuration value is made in exactly one place.

Andy Hunt and Dave Thomas formulated the principle in The Pragmatic Programmer in 1999. They framed it as a rule about knowledge, not about text: two identical lines of code are not necessarily a violation, while one rule expressed differently in a database schema, a validator and documentation is. That distinction is the most frequently misunderstood aspect of DRY.

What counts as duplicated knowledge

DRY targets duplication of decisions. A decision is anything that would have to change together if requirements changed: the maximum length of a username, the formula for value-added tax, the shape of an API payload. When such a decision lives in two places, the copies will drift apart over time, and the system starts to contradict itself.

Duplication arises in several ways, and each needs a different remedy. Hunt and Thomas distinguished duplication that is imposed by the environment, inadvertent, caused by impatience, or created by several developers working in parallel. The table below groups the common forms by where they appear.

Form of duplicationExampleTypical remedy
Logic duplicationSame discount rule in two servicesExtract a shared function or module
Data duplicationCustomer address stored in two tablesNormalize or define one source of truth
Schema duplicationField list repeated in code, SQL and API specGenerate code from one schema definition
Configuration duplicationSame URL in several config filesCentral configuration with references
Documentation duplicationComments restating the codeSelf-documenting names, generated docs
Forms of duplication and typical remedies

Techniques for applying DRY

The basic tool is abstraction: give the repeated knowledge a name and refer to it. Functions, constants, modules, base types and shared libraries all serve this purpose. At larger scale, code generation keeps database migrations, client SDKs and validation rules in step with one canonical definition such as an OpenAPI document or a Protocol Buffers file.

Architectural patterns support the same goal. Separation of concerns gives each rule a natural home, the repository pattern centralizes data access, and dependency injection lets one implementation serve many consumers. The following table matches the technique to the scale of the problem.

ScopeTechniqueWhat stays single-sourced
ExpressionNamed constant or variableA literal value or threshold
FunctionExtracted helper or higher-order functionA calculation or algorithm
ModuleShared library or domain serviceA business rule or policy
SystemSchema-first code generationData contracts between components
InfrastructureTemplates and infrastructure as codeEnvironment and deployment settings
DRY techniques by scope

How DRY relates to neighboring principles

DRY is often cited together with KISS, YAGNI and the SOLID principles, and the interaction among them matters in practice. Removing duplication usually adds an abstraction layer, and every abstraction has a cost in indirection, so DRY must be weighed against simplicity and present need.

PrincipleCore questionTension with DRY
KISS principleIs this the simplest workable designAbstractions can add complexity
YAGNIIs this needed right nowPremature generalization violates it
Single responsibilityDoes this unit have one reason to changeUsually reinforces DRY
Separation of concernsAre distinct concerns kept apartShared code can couple concerns
WETWrite everything twice, a deliberate counterpointTolerates copies until a pattern is clear
DRY compared with related design principles

A widely used heuristic, the rule of three, resolves much of this tension: tolerate a second copy, and extract an abstraction when the third appears. By then the common pattern and its variations are visible, which lowers the risk of designing the wrong abstraction.

When applying DRY goes wrong

The most damaging misuse is merging code that looks alike but represents different knowledge. Two validation functions may share their logic today because invoicing and shipping currently use the same postal format, yet the two rules belong to different domains and will evolve separately. Forcing them into one function creates accidental coupling.

Such false abstractions accumulate flags and parameters as each caller needs a slight variation, until the shared code is harder to change than the copies would have been. Sandi Metz summarized the lesson by observing that duplication is far cheaper than the wrong abstraction. In microservice and domain-driven design, teams often accept duplicated code across bounded contexts to preserve independent deployment.

Warning signLikely causeCorrective action
Shared function has many boolean flagsDifferent concepts mergedSplit back into separate functions
One change breaks unrelated featuresAccidental couplingDuplicate, then let each copy evolve
Teams wait on a shared library releaseCross-team dependencyAccept local copies per bounded context
Same rule fixed in one place but not anotherGenuine DRY violationConsolidate into one authoritative source
Warning signs and corrective actions
  • Ask whether the copies would always change together; if not, they are not duplication.
  • Prefer duplication in tests when it makes each test readable on its own.
  • Treat generated artifacts as outputs, never edit them by hand.

Understanding it simply

The DRY principle says that each fact should be written down once. Think of a family that keeps its emergency phone numbers on one sheet on the refrigerator. If the doctor’s number changes, someone updates one sheet, and everybody sees the new number.

If the same number were copied into five notebooks, one of them would eventually be wrong. Software works the same way. One source of truth keeps the whole system consistent. The catch is that two numbers which merely look similar are not the same fact, and they should not be forced onto one line.

Applied in practice

An online retailer defined the rule “orders above 50 dollars ship free” in four places: the checkout service, the mobile app, the email templates and a marketing banner. When the threshold moved to 75 dollars, only three locations were updated, and for two weeks the app promised free shipping that checkout did not grant, generating hundreds of support tickets.

The architecture team moved the threshold into a single pricing policy service that exposes the value through an API, and the app, templates and banner now read it at run time. The next change took one configuration update and appeared everywhere within minutes.

The same team deliberately left the address validation code duplicated between billing and warehouse systems, because those rules belong to different domains. That choice later allowed the warehouse to adopt a new carrier format without touching billing code.