Fact-checked by Grok 2 weeks ago

Don't repeat yourself

"Don't Repeat Yourself" (DRY) is a fundamental principle in that states every piece of knowledge must have a single, unambiguous, authoritative representation within a . This approach aims to eliminate redundancy across code, documentation, data structures, and processes, ensuring that changes need to be made in only one place to maintain consistency and accuracy. The principle was introduced by Andrew Hunt and Dave Thomas in their 1999 book The Pragmatic Programmer: From Journeyman to Master, where it is presented as a core tip for pragmatic software development. Beyond mere code duplication, DRY extends to avoiding repeated information in comments, tests, specifications, and even team practices, promoting abstraction and modularization to centralize knowledge. For instance, instead of copying logic across multiple functions, developers are encouraged to create reusable components or use techniques like inheritance and composition. Adhering to offers several key benefits, including reduced maintenance effort, as updates propagate automatically through shared representations, minimizing the risk of errors from overlooked duplications. It also enhances code readability and reusability, fostering more efficient development workflows and scalable systems. However, applying requires balance, as over-abstraction can sometimes complicate simple code without proportional gains. In practice, is widely applied in , via normalization, and modern frameworks like , which explicitly incorporate it to keep code concise and maintainable.

Definition and Origins

Core Definition

The Don't Repeat Yourself (DRY) principle is a foundational guideline in that advocates for eliminating duplication of to ensure consistency and efficiency across a system. Formulated by Andrew Hunt and Dave Thomas, it asserts: "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." This approach counters the risks associated with redundant information, where inconsistencies can lead to errors during maintenance or updates. DRY achieves this by encouraging the use of abstractions—such as functions, modules, or configurations—to encapsulate repeated logic or , thereby centralizing changes in one authoritative location. When duplication occurs, updating one instance without propagating changes to others introduces bugs and increases complexity; DRY mitigates this by promoting a , which simplifies and evolution of the system. The Single Choice Principle represents a specific application of DRY, where alternatives or decisions are centralized to avoid . The scope of extends beyond code to include , where normalization techniques eliminate redundant data to prevent anomalies; , to avoid conflicting descriptions; and processes like build systems or testing, ensuring procedural knowledge is not scattered. Ultimately, the principle aims to minimize duplication, fostering systems that are easier to maintain, scale, and modify over time.

Historical Development

The DRY (Don't Repeat Yourself) principle was coined by Andrew Hunt and Dave Thomas in their 1999 book : From Journeyman to Master, where they presented it as a core guideline for avoiding duplication in software systems to enhance and reduce errors. In the book, they defined DRY broadly to encompass not just but also , processes, and knowledge representation, stating that "every piece of knowledge must have a single, unambiguous, authoritative representation within a system." This initial formulation emerged in the late 1990s during a period of increasing focus on pragmatic and agile methodologies, which emphasized practical, iterative development over rigid, repetitive practices. Early conceptual influences included techniques pioneered by E. F. Codd in the 1970s, whose rules aimed to eliminate through structured . Similarly, principles, as outlined by in 1972, promoted system breakdown into independent modules to minimize repetitive logic and improve reusability. A precursor idea, the Single Choice Principle introduced by in the 1980s, advocated for centralized decision points in object-oriented design to avoid scattered repetitions. Following its introduction, DRY spread rapidly through the pragmatic programming movement, influencing the adoption and practices within communities of dynamic languages like Ruby and Python in the early 2000s. Ruby on Rails, launched in 2004, exemplified this adoption by embedding DRY into its convention-over-configuration philosophy to streamline web development. In Python communities, DRY became a staple for promoting reusable functions and modules, aligning with the language's emphasis on readability and efficiency; for example, the Django web framework, released in 2005, explicitly incorporates DRY principles. By the 2010s, the principle expanded beyond traditional coding to broader applications, such as in , where it guided the automation of to prevent repetitive configurations across environments. This evolution reflected DRY's integration into modern workflows, solidifying its role in reducing systemic duplication.

Core Principles

Single Choice Principle

The Single Choice Principle, introduced by , states that whenever a must support a set of alternatives, one and only one module in the system should know their exhaustive list. This centralization ensures that the knowledge of variants is confined to a single location, promoting and facilitating system evolution without scattered updates. The principle emerged in the as part of the foundational design guidelines for , particularly in the development of the Eiffel language, predating the formal articulation of the principle. In Eiffel, it is exemplified by the single dispatch mechanism, where method selection is handled dynamically based on the type of the target object, avoiding duplicated conditional logic across multiple modules. By enforcing a unique decision point for alternatives, the Single Choice Principle directly supports the broader philosophy by eliminating redundant representations of choices, thereby preventing inconsistencies that arise from maintaining duplicate in code.

Relation to Abstraction and Normalization

The Don't Repeat Yourself () principle implements by encapsulating repeated logic into reusable constructs such as functions, classes, or macros, ensuring that modifications to shared occur in a single location. This approach transforms duplicated code segments into an authoritative , reducing the risk of inconsistencies that arise from maintaining multiple copies. For instance, extracting common validation routines into a dedicated method allows developers to update rules centrally, aligning with DRY's emphasis on unambiguous . In database design, DRY manifests through data normalization, which organizes relational data to eliminate redundancy by adhering to normal forms like first normal form (1NF), second normal form (2NF), and third normal form (3NF). Normalization achieves this by decomposing tables to store each piece of information once, preventing anomalies from update, insertion, or deletion operations that could otherwise propagate errors across redundant entries. As articulated in the foundational relational model, this process ensures that non-key attributes depend solely on the primary key, creating a single source for data facts and embodying DRY's goal of authoritative storage. DRY extends to configuration management by advocating a single source of truth for settings, such as using centralized environment variables or configuration files rather than embedding values directly in code. This practice avoids scattering identical parameters across modules, which could lead to synchronization issues during changes, and instead promotes a unified repository that all components reference. Beyond mere avoidance of copy-pasting, DRY prioritizes establishing an authoritative representation of knowledge, where repetition signals underlying design flaws requiring abstraction or restructuring rather than superficial elimination. This distinction underscores the principle's philosophical tie to the Single Choice Principle, focusing on conceptual unity over tactical duplication removal.

Applications

In Software Code

In software code, the Don't Repeat Yourself (DRY) principle addresses code duplication, where identical or similar logic appears in multiple places, increasing maintenance costs and error risks. For instance, repeating validation logic—such as checking email formats across various functions—can lead to bugs if one instance is updated without modifying the others, resulting in inconsistent behavior and heightened vulnerability to defects. To apply DRY, developers refactor duplicates into reusable components, such as extracting common logic into functions, modules, or classes that leverage hierarchies for shared behavior. This approach centralizes changes, ensuring updates propagate reliably and reducing the overall size. For example, in a handling multiple endpoints like and registration, duplicating user checks (e.g., verifying credentials and session tokens) in each can be refactored into a single shared service or , invoked across routes to enforce consistency. Language-agnostic patterns illustrate DRY's versatility beyond specific validations. Hard-coded lists, like repeating arrays of weekday names in reporting or scheduling code, can be consolidated into a single constant or configuration, iterated via loops to avoid manual replication. Similarly, for user interface elements, templating systems enable reusable snippets—such as a standard form layout for inputs and buttons—preventing copy-pasted or markup that would otherwise fragment styling and logic updates. Detecting duplication informally involves developer practices like visual code reviews during pull requests or pairwise programming sessions, where similarities in structure or logic are spotted manually. Complementing these, code similarity tools analyze source files to quantify overlap, such as line-by-line matches exceeding a , guiding targeted refactoring without requiring exhaustive automated scans.

In Documentation and Processes

The principle extends to documentation by advocating for a single authoritative source of truth for project-related knowledge, such as setup instructions, to avoid inconsistencies arising from duplicated content across multiple files or repositories. For instance, maintaining one comprehensive file or a centralized wiki page ensures that all team members reference the same instructions for environment configuration, dependency installation, and deployment steps, reducing the risk of outdated or conflicting information. This application aligns with the original definition from , where every piece of system knowledge must have a unique representation to facilitate maintenance and clarity. In processes, DRY manifests through standardized workflows that reuse components rather than replicating steps, particularly in and (CI/CD) pipelines. Build steps, such as testing scripts or security scans, are defined once in template files and included or extended across projects, as exemplified in GitLab's use of YAML anchors and the include keyword to modularize .gitlab-ci.yml configurations for jobs like and deployment. This reusability minimizes errors from manual replication and streamlines updates, promoting efficiency in large-scale environments. For testing practices, encourages shared fixtures or setup data to eliminate duplication in test cases, allowing common preparations like or database initialization to be defined once and invoked as needed. In frameworks like , custom fixtures encapsulate repetitive logic—such as logging in to an application—into reusable functions that multiple tests can extend, adhering to the principle by centralizing setup code and reducing boilerplate. This approach, supported by CI platforms like , ensures tests remain maintainable without embedding identical initialization blocks in each file, fostering reliability in automated testing suites. In agile teams, supports a unified source for requirements documentation to mitigate miscommunication, such as storing user stories and acceptance criteria in a single tool like rather than scattering them across emails or disparate notes. This single representation of project knowledge enhances collaboration during sprints, aligning development efforts and reducing rework from ambiguous specifications. Integrating with agile methodologies can improve team productivity through such standardized practices. The relevance of in and processes has grown since the , paralleling the rise of and , where distributed systems demand reusable configurations to manage across services. This evolution underscores DRY's role in scalable workflows, evolving from its 1999 origins to address modern operational challenges.

Alternatives and Contrasts

WET Principle

The principle, standing in direct opposition to the DRY principle's emphasis on avoiding repetition, represents an characterized by unnecessary duplication in and implementation. It is often invoked humorously to critique codebases where the same logic or information is redundantly expressed across multiple locations, increasing and proneness. Common backronyms for include "Write Everything Twice," "We Enjoy Typing," and "Waste Everyone's Time," underscoring the inefficiency and frustration it embodies in development practices. These terms highlight how manifests as either deliberate choices for quick fixes or inadvertent oversights, frequently observed in environments with isolated architectural layers such as , , and data access tiers. The concept of emerged in programming communities around the early as a satirical to , particularly in discussions critiquing duplication in systems and multi-tiered applications where changes propagate inconsistently across siloed components. This typically arises from prioritizing short-term development speed—such as copying code to meet immediate deadlines—over long-term , which can entangle dependencies and evolve into disorganized structures akin to . In contrast to related ideas like the AHA principle, which warns against premature generalization, WET specifically targets explicit, avoidable repetition that undermines system .

AHA Principle

The principle, an acronym for "Avoid Hasty Abstractions," serves as a cautionary complement to the principle by urging developers to delay generalizations until the underlying requirements and use cases are sufficiently understood, thereby prioritizing adaptability over premature optimization. This approach emphasizes thoughtful abstraction—either during initial system design or only when patterns emerge clearly—rather than impulsively refactoring duplicates to enforce "once and only once" without evidence of evolving needs. Coined by software engineer in 2019 and further popularized through discussions in the programming community, AHA refines DRY by advising that duplication should be tolerated temporarily if it signals a genuine, recurring requirement rather than an anticipated but unrealized change. The rationale behind stems from the recognition that aggressive application of can result in fragile codebases, where early s force future modifications into convoluted conditionals and parameters that obscure and increase costs. For instance, when requirements evolve unexpectedly, a hastily created —designed to eliminate initial duplicates—may require extensive alterations, such as adding if statements to handle variations, leading to code that is harder to comprehend and extend than straightforward duplication would have been. This fragility often arises from the , where developers invest in and preserve flawed abstractions, complicating subsequent refactoring and violating the very goals of . In relation to , does not reject the elimination of repetition outright but tempers it by recommending only when duplication demonstrates a stable, shared behavior across contexts, thus avoiding over-engineering that anticipates changes which may never occur. This nuanced stance promotes a flexible, mistake-tolerant development process, where initial duplication allows for easier iteration and clearer code organization as true patterns reveal themselves over time.

Benefits and Challenges

Advantages

Adhering to the Don't Repeat Yourself (DRY) principle enhances software maintainability by establishing a single source of truth for shared knowledge or logic, allowing updates to be made in one location rather than across multiple duplicated instances, which minimizes the risk of introducing inconsistencies or errors during modifications. This centralized approach directly supports error reduction, as seen in scenarios where a single validation rule or business logic component is updated once to prevent divergent implementations that could lead to bugs in other parts of the system. In an industrial case study involving refactoring cross-project code duplication across 62 applications, the effort removed an average of 38% of duplicated code and 1,958 lines in total, resulting in improved maintainability through reduced technical debt and more streamlined updates. Similarly, an empirical study of 332 refactoring commits in 128 open-source Java projects found that duplication-aware refactoring positively impacts structural quality metrics related to maintainability and understandability, as evidenced by developer commit messages. The principle also promotes and by decreasing code volume and , enabling developers to grasp the system's more quickly without navigating repetitive sections. This reduction in aids , as extending functionality—such as adding new features—requires modifications in fewer places, avoiding the need to synchronize changes across duplicates and facilitating growth in larger systems. Empirical evidence underscores these advantages, with the same industrial refactoring yielding a 33% improvement in by packaging duplicated features into shared components, leading to efficiency gains in subsequent phases due to gained experience and reduced repetition. At , analysis of refactored modules showed that those addressing issues like duplication exhibited 7% fewer post-release defects compared to non-refactored ones and reduced inter-module dependencies by a factor of 0.85, correlating with higher in evolving projects.

Common Pitfalls

One common pitfall in applying the DRY principle is over-abstraction, where developers hastily create complex hierarchies or reusable components to eliminate minor duplications, resulting in code that is difficult to understand and modify. This often leads to "," a state where abstractions accumulate unnecessary conditionals and parameters, making the system rigid and prone to errors when requirements evolve. Such wrong abstractions mix unrelated ideas, increasing and maintenance costs, as the initial solution no longer aligns with current needs. Another frequent mistake is ignoring contextual differences when enforcing across unrelated domains, which can introduce tight between components that should remain . For instance, merging code that appears similar but serves distinct purposes—such as user interface logic with data processing—violates and complicates future changes. This approach treats superficial similarities as opportunities for unification without considering the broader system architecture, leading to brittle designs. Measurement challenges also hinder effective DRY application, particularly in detecting true duplication versus coincidental similarities that do not represent shared . Automated tools may flag incidental duplications—code that looks alike by chance but encodes different intents—as violations, prompting unnecessary refactoring that obscures the original . Distinguishing essential duplication (repeated ) from incidental cases requires manual review, which is time-intensive and prone to oversight in large codebases. In team settings, inconsistent enforcement of often arises due to varying interpretations among developers, leading to partial adoption and reversion to duplicated code (sometimes termed "" practices). Without clear guidelines or code reviews, individual preferences dominate, fragmenting the and undermining collective . To mitigate these pitfalls, practitioners recommend the guideline of "duplicating until it hurts," abstracting only after repetition causes tangible maintenance issues, which aligns with the (Avoid Hasty Abstractions) principle as a counterbalance to premature enforcement. When a wrong abstraction emerges, the remedy involves inlining the to reintroduce controlled duplication, allowing context-specific adaptations without retaining flawed generalizations. For teams, establishing shared review processes and focusing on knowledge duplication rather than syntactic matches helps sustain consistent application.

References

  1. [1]
    [PDF] The Pragmatic Programmer
    ... Don't Repeat Yourself. Many people took it to refer to code only: they thought that DRY means “don't copy-and-paste lines of source.” That is part of DRY ...Missing: engineering origin
  2. [2]
    The Pragmatic Programmer, 20th Anniversary Edition
    4-day returnsThis new edition examines the core of modern software development—understanding what is wanted and producing working, maintainable code that delights its users ...
  3. [3]
    Basic Design Principles in Software Engineering - IEEE Xplore
    ... Don't repeat Yourself Principle, Liskov Substitution Principle, and Dependency Inversion Principle. ... Principle, and Dependency Inversion Principle ...
  4. [4]
    [PDF] Agile Web Development with Rails 6 - Pragmatic Bookshelf
    A major philosophical underpinning of Rails that keeps code short and read- able is the DRY principle, which stands for Don't Repeat Yourself (see The.
  5. [5]
    DRY Principle in Software Development - GeeksforGeeks
    Aug 27, 2025 · When developers adhere to the DRY principle, they aim to create reusable components, functions, or modules that can be utilized in various parts ...
  6. [6]
    DevOps and the DRY Principle - DZone
    Oct 13, 2018 · DevOps and DRY (Don't Repeat Yourself) embrace the ideals that you should only write quality code once, the first time.
  7. [7]
    [PDF] Object-Oriented Software Construction, 2nd edition (entire text from ...
    A whole generation was introduced to object technology through the first edition of Bertrand Meyer's OOSC. This long-awaited new edition retains the ...
  8. [8]
    ET: Inheritance - Eiffel
    In contrast, using the combination of inheritance, redefinition, polymorphism and dynamic binding makes it possible to have a point of single choice -- a unique ...Missing: dispatch | Show results with:dispatch
  9. [9]
    Don't Repeat Yourself (DRY) - Principles Wiki
    Aug 31, 2025 · See section contrary principles. Origin. Andrew Hunt and David Thomas: The Pragmatic Programmer: From Journeyman to Master. Evidence. Examined ...
  10. [10]
    artima - Orthogonality and the DRY Principle
    ### Summary of DRY Principle from http://www.artima.com/intv/dry.html
  11. [11]
    [PDF] A Relational Model of Data for Large Shared Data Banks
    This paper is concerned with the application of ele- mentary relation theory to systems which provide shared access to large banks of formatted data. Except for ...Missing: DRY | Show results with:DRY
  12. [12]
    DRY Software Design Principle | Baeldung on Computer Science
    Jun 17, 2023 · It's a software development principle with the goal of removing logic duplication. DRY was first introduced in the book The Pragmatic Programmer ...
  13. [13]
    [PDF] Avoiding Repetition
    Take a simple example: subroutine calls. You use a subroutine when you realize that two blocks of code, in different places, are or will be the same.
  14. [14]
    DRY development: A cheatsheet on reusability throughout GitLab
    Jan 3, 2023 · DRY development: A cheatsheet on reusability throughout GitLab. How to follow the DevOps principle of 'don't repeat yourself' to optimize CI/CD.
  15. [15]
    CI/CD best practices - Buildkite
    Aug 24, 2023 · The DRY principle, commonly known as "Don't Repeat Yourself", encourages software engineers to reduce repetition within their code. Similarly, ...
  16. [16]
    Reuse code with custom test fixtures in Playwright - Checkly Docs
    Repeating login logic in every test is inefficient and violates the DRY (Don't Repeat Yourself) principle. Let's implement a fixture to reuse and share code ...
  17. [17]
    Playwright fixtures: A deep dive - CircleCI
    Jul 15, 2025 · ... tests that they are called in. Reduce repetition: Fixtures ensure that the DRY (Don't Repeat Yourself) principles are upheld as they serve ...<|separator|>
  18. [18]
    Integrating DRY Principle with Agile for Better Productivity - MoldStud
    Oct 16, 2025 · Explore how integrating the DRY principle with Agile methodologies can streamline processes and improve project delivery in software ...
  19. [19]
    The Ten Commandments of Microservices - The New Stack
    Jan 25, 2016 · This is closely aligned with the principle of “don't repeat yourself” (DRY), which states that every piece of knowledge must have a single ...
  20. [20]
    Is this redundant? - Stack Overflow
    Jul 10, 2019 · Violations of DRY are typically referred to as WET solutions, which is commonly taken to stand for either "write everything twice", "we ...
  21. [21]
    Name of this repeated definitions replaced by overloaded functions ...
    Jul 21, 2023 · ... dry-do-not-repeat-yourself. Violations of DRY are referred to as WET: We Enjoy Typing, Write Everything Twice, Waste Everyone's Time.
  22. [22]
    Is there an established name for this anti-pattern? - Stack Overflow
    Feb 19, 2020 · Violations of DRY are typically referred to as WET solutions, which is commonly taken to stand for "write every time", "write everything twice ...
  23. [23]
    AHA Programming - Kent C. Dodds
    Jun 22, 2020 · DRY. DRY (an acronym for "Don't Repeat Yourself"), is an old software principle that Wikipedia sums up like this: Every piece of knowledge ...
  24. [24]
    Avoiding Hasty Abstractions (AHA programming) - DEV Community
    Jan 10, 2023 · When I said we should avoid hasty abstractions, what I meant was that we should try not to abstract impulsively. Thoughtful abstractions are ...
  25. [25]
    The Wrong Abstraction - Sandi Metz
    Jan 20, 2016 · ... prefer duplication over the wrong abstraction This small section of a much bigger talk invoked a surprisingly strong reaction. A few folks ...
  26. [26]
    [PDF] An Empirical Study of Refactoring Challenges and Benefits at ...
    This paper presents a field study of refactoring benefits and challenges at Microsoft through three complementary study methods: a survey, semi-structured.Missing: gain | Show results with:gain<|control11|><|separator|>
  27. [27]
    Refactoring cross-project code duplication in an industrial software ...
    The objective of this work was to investigate the impact of refactoring cross-project duplicated code on maintainability, code reuse, and technical debt.
  28. [28]
    An Empirical Study on the Impact of Code Duplication-aware ... - arXiv
    Feb 6, 2025 · An Empirical Study on the Impact of Code Duplication-aware Refactoring Practices on Quality Metrics. Authors:Eman Abdullah AlOmar.
  29. [29]
    Software Quality From First Principles - Ryan Barkley
    May 25, 2020 · ... DRY-rot”. Good abstractions are an important part of scaling a codebase to support new features, but having no abstraction is usually ...
  30. [30]
    Why is DRY important? - Software Engineering Stack Exchange
    Aug 24, 2011 · The DRY principle as mentioned by Andy Hunt and Dave Thomas isn't limited to preventing duplication of code. It also advocates code generation ...
  31. [31]
    The DRY Principle and Incidental Duplication - Anthony Sciamanna
    Jul 28, 2018 · The DRY principle is credited to Andy Hunt and Dave Thomas. The term first appeared in their book The Pragmatic Programmer, where they gave the ...
  32. [32]
    Dev Principle #11: DRY - Don't Repeat Yourself - Fresh Consulting
    Oct 17, 2017 · One way to maintain and stabilize your code is to adhere to the “DRY” Principle: Don't repeat yourself. ... Maintain good communication and ...