What is the DRY Principle? – ITU Online IT Training

What is the DRY Principle?

Ready to start learning? Individual Plans →Team Plans →

como é o dry é a pergunta certa quando seu código começa a repetir regras, constantes e validações em vários lugares. O DRY principle (“Don’t Repeat Yourself”) exists to cut maintenance overhead, reduce inconsistent fixes, and keep one clear source of truth for logic that should change together. This guide explains what DRY means, where it came from, how to apply it in real projects, and when repeating code is actually the better choice.

Quick Answer

The DRY principle, or “Don’t Repeat Yourself,” is a software design rule that says every piece of business logic, knowledge, or configuration should live in one clear place. That makes code easier to maintain, less error-prone, and simpler to update when requirements change. The key is centralizing meaningful logic, not deleting every repeated line.

Definition

DRY (Don’t Repeat Yourself) is a software engineering principle that says each piece of knowledge should have a single, unambiguous representation in a codebase. In practice, that means one source of truth for rules, validation, constants, and configuration that should always stay in sync.

ConceptDRY principle as of July 2026
Full FormDon’t Repeat Yourself as of July 2026
OriginIntroduced by Andy Hunt and Dave Thomas in The Pragmatic Programmer as of July 2026
Primary GoalReduce duplication of knowledge and logic as of July 2026
Main BenefitLower maintenance overhead and fewer inconsistent changes as of July 2026
Common RiskOver-abstraction that hurts readability as of July 2026
Related IdeasKISS, SOLID, modular design, and refactoring as of July 2026

What Is the DRY Principle?

DRY is a design principle that says a codebase should avoid repeating the same knowledge in multiple places. That “knowledge” can be a business rule, a validation rule, a magic number, an API payload shape, or even a formatting rule used by several features. If one requirement changes, you want one place to update, not five copies scattered across the project.

This is why como é o dry is not just about removing duplicate lines of code. It is about removing duplicated meaning. Two chunks of code can look different and still be duplicates if they encode the same rule in two places.

Think about a discount rule that says orders above $100 get free shipping. If that rule appears in checkout, admin reporting, and a background job, the first update will be easy to miss. DRY reduces that risk by keeping the rule in a shared function, service, or configuration object.

Simple before-and-after example

Here is the pattern DRY tries to fix. The first version repeats the same logic in multiple places, which creates drift when one copy changes and the others do not.

  • Before DRY: the tax rate appears in several invoice calculations.
  • Before DRY: email validation is copied into registration and profile update flows.
  • Before DRY: hardcoded status labels are repeated in frontend and backend code.
  • After DRY: the tax rate lives in one shared constant or service.
  • After DRY: one validation function is reused everywhere the rule applies.

That shift improves readability because developers stop hunting through multiple files to understand one rule. It also improves consistency, which matters every time a team ships changes under time pressure. For background on code structure and maintainability, Software Engineering is the broader discipline that DRY supports.

“Duplicated knowledge is expensive because every change becomes a search problem, not a single edit.”

Where Did DRY Come From?

DRY was popularized by Andy Hunt and Dave Thomas in The Pragmatic Programmer, first published in 1999. They used the idea to push developers toward systems where knowledge is expressed once and reused deliberately, rather than copied by habit. That message landed because software teams were already dealing with rising complexity, more integration points, and faster change cycles.

The historical context matters. As systems grew, duplicated logic turned into a maintenance tax. A small rule change could ripple across multiple files, services, or teams. That meant more bugs, more regression risk, and more time spent verifying that every copy was updated correctly.

DRY became a foundational idea because it solved a practical engineering problem: how do you reduce the cost of change? In modern software teams, that question is still central. The principle aligns with the goals of fewer defects, faster delivery, and cleaner code ownership across multiple developers.

Why the principle stuck

Teams keep returning to DRY because the pain of duplication never really goes away. A duplicated rule may look harmless on day one, but it becomes a liability once business logic changes. That is especially true in systems with frequent releases, distributed teams, or long-lived applications.

  • Change impact: one rule change should not require a scavenger hunt.
  • Team efficiency: developers should not rewrite the same logic repeatedly.
  • Quality control: fewer copies means fewer opportunities for drift.

If you want a broader reference point on real-world software roles and the scale of maintenance work, the U.S. Bureau of Labor Statistics notes continued demand for software developers and quality-focused engineering work in its occupational outlook resources at BLS Software Developers as of July 2026.

Why Does Code Duplication Become a Problem?

Code duplication becomes a problem because software changes over time, while copied logic tends to drift. One copy gets updated, one gets forgotten, and now the application behaves differently depending on which path a user hits. That inconsistency is exactly how subtle bugs survive code review and show up in production.

Duplication also increases maintenance overhead. Every repeated rule adds another place to test, another place to document, and another place to refactor later. In a small project, that may be annoying. In a large codebase with multiple contributors, it becomes expensive.

Common failure patterns

These are the kinds of duplicates that usually cause real pain:

  • Validation logic: one form checks password length one way, another checks it differently.
  • Formatting rules: dates, phone numbers, and currency strings are assembled by hand in several places.
  • Hardcoded constants: tax rates, API version strings, and role names are copied across modules.
  • Business rules: discounts, shipping thresholds, or access rules are repeated in multiple services.

That drift is especially dangerous when the code looks “close enough.” Two similar blocks may pass testing in isolation, but fail when requirements change. The result is a bug that is hard to trace because the broken behavior is not caused by one obvious mistake; it is caused by a missed copy.

Warning

Duplicated business rules are more dangerous than duplicated syntax. Repeated syntax wastes time, but repeated logic can create inconsistent results that are hard to detect in production.

For a standards-based view of maintainable systems, the NIST SP 800-160 guidance on systems security engineering reinforces the value of disciplined design, traceability, and reducing ambiguity as of July 2026.

What Are the Core Ideas Behind DRY?

The core idea behind DRY is that knowledge should have one authoritative representation. That does not mean every repeated character is bad. It means anything that represents a shared rule, policy, or behavior should be centralized so the codebase has a single change point.

This distinction matters because developers often confuse “same code” with “same knowledge.” Two functions can share similar structure but serve different business contexts. In that case, forcing them into one abstraction can damage clarity. DRY is about meaning, not just text.

Knowledge versus repetition

A repeated if-statement is not automatically a DRY violation. If the logic is tied to two genuinely different workflows, keeping them separate may be the cleanest design. But if both blocks express the same policy, centralization is the better choice.

That is where modular design becomes important. When logic is broken into focused units, each module can own one responsibility. A shared validation routine, pricing service, or formatting utility can then be reused without exposing implementation details everywhere.

  • One source of truth: update the rule in one place.
  • Clear boundaries: keep domain logic inside the right layer.
  • Low coupling: shared code should not force unrelated changes.
  • High cohesion: grouped logic should belong together.

This is also where the glossary concept of Modular Design fits naturally. DRY works best when modules are small enough to be reusable and clear enough to be understood quickly. The goal is not fewer files at all costs. The goal is fewer change points with better structure.

DRY vs. Reuse: What’s the Difference?

Reuse is the act of using the same function, component, or module in more than one place. Duplication is copying the same logic or behavior into multiple places. DRY encourages reuse, but the two are not identical. A reusable abstraction is useful only when it truly represents shared behavior.

The practical difference is this: reuse is a tool, DRY is the rule that guides when to use it. A shared helper can reduce duplication, but a badly designed helper can create hidden complexity. If developers have to guess what the helper does from ten arguments and six condition flags, the cure may be worse than the disease.

When reuse helps

Reuse works well when the same rule is stable and used often. Common examples include:

  • Shared functions: a single slug generator used across features.
  • Shared components: a button or alert pattern used in multiple screens.
  • Shared services: one API client that handles retries and headers consistently.

When reuse becomes a trap

Two blocks that look similar today may diverge tomorrow. If you merge them too early, you can create a fragile abstraction that tries to serve too many use cases. That is the classic “one-size-fits-all” mistake.

A good rule of thumb is to compare change patterns, not just current code shape. If two copies change together for the same reason, they probably belong together. If they only look alike because of a temporary implementation detail, keep them separate until the pattern proves stable.

ReuseUsing one shared unit in multiple places when the behavior is truly common
DuplicationCopying logic into multiple places, which increases maintenance risk

How Does DRY Work in Real Projects?

DRY works in real projects by moving repeated knowledge into a stable, shared location. That can be a function, class, module, configuration file, database constraint, or UI component. The exact form depends on the stack, but the goal stays the same: one change point for one rule.

  1. Find repetition: look for repeated conditions, constants, formatting, or validation logic.
  2. Identify the shared knowledge: ask what rule or policy those copies are expressing.
  3. Extract carefully: move the rule into a function, service, component, or config object.
  4. Use clear names: make the abstraction obvious to other developers.
  5. Verify behavior: test the centralized logic so every consumer stays correct.

That workflow works during bug fixes as well. If you fix the same issue in two places, you have probably discovered a DRY opportunity. Refactor while the context is fresh. The best time to centralize a rule is when the cost of duplication becomes visible.

Examples of common DRY refactors

  • Constants: move repeated API endpoints, tax rates, or role names into a config file.
  • Validation: create one email or password validator instead of duplicating checks.
  • Request logic: centralize headers, retry handling, and base URLs in one API client.
  • Formatting: use one date formatter across reporting screens and exports.

Environment values are another common place where duplication creeps in. Repeating hardcoded settings across files makes deployment harder and increases the chance of drift. The glossary term Environment Variables is relevant here because they let teams centralize environment-specific values instead of scattering them through source code. For reference on software architecture and quality practice, ISO 9001 quality management principles are often used as a broader quality lens, while engineering teams usually apply the same discipline inside code and configuration.

What Are Practical Techniques for Writing DRY Code?

Writing DRY code means choosing the right level of abstraction for the job. You do not need a giant framework or a shared utility for every repeated line. You need a deliberate place to put logic that truly belongs in one place.

Use small, focused abstractions

Start by extracting repeated behavior into a function with clear inputs and outputs. If the code depends on external state, make that dependency explicit. Clear function names matter more than clever ones because other developers need to understand the rule quickly.

  • Helper methods: use them for repeated formatting and transformation logic.
  • Shared services: use them for business rules that multiple parts of the app consume.
  • Reusable components: use them for repeated UI patterns like forms, alerts, and cards.
  • Templates and partials: use them for repeated page structure in web applications.

Centralize rules where they belong

Not every duplicate belongs in code. Some rules belong in configuration, a schema, or a database constraint. If the data layer can enforce a rule more reliably than application code, put it there. That keeps the rule closer to the data and reduces the chance of bypassing it in one code path.

For frontend development, DRY often means component-based reuse. A shared button component keeps spacing, disabled behavior, and accessibility attributes consistent. A shared form field component keeps labels, error display, and helper text aligned across the UI. That is not just cleaner code; it is easier maintenance.

Pro Tip

Name abstractions after the business rule they represent, not the implementation detail they hide. “TaxCalculator” is clearer than “SharedUtils2,” and “PasswordPolicy” is clearer than “ValidationHelper.”

For frontend standards and accessibility expectations, the W3C Web Accessibility Initiative is a strong reference point when shared UI components must stay consistent and usable as of July 2026.

How Do DRY, KISS, and SOLID Work Together?

DRY, KISS (“Keep It Simple, Stupid”), and SOLID are related but not interchangeable. DRY focuses on avoiding duplicated knowledge. KISS focuses on keeping design simple. SOLID provides object-oriented design guidance that helps systems stay maintainable as they grow.

The healthiest code often follows all three. DRY keeps rules centralized. KISS prevents those shared rules from becoming over-engineered. SOLID helps structure classes and interfaces so each part of the system has a clear job.

Where the principles support each other

  • Single Responsibility: a class or module with one job is easier to reuse cleanly.
  • Open/Closed: code can extend without duplicating every existing path.
  • KISS: simple code is easier to read, test, and trust.
  • DRY: one rule, one place, one update.

The conflict happens when a developer pursues DRY so aggressively that the abstraction becomes harder to understand than the original repetition. In that case, KISS should win. Principles are decision aids, not hard laws. A small amount of repetition can be acceptable if it preserves clarity and reduces cognitive load.

“The best design choice is the one that reduces future confusion without creating present complexity.”

For a broader framework on structure and responsibility in systems, CISA software development guidance emphasizes secure, maintainable engineering practices that align with disciplined code organization as of July 2026.

When Is It Okay to Repeat Code?

It is okay to repeat code when abstraction would make the system harder to understand than the duplication itself. That sounds counterintuitive, but it is often the right call. Early-stage projects, for example, usually need flexibility more than shared frameworks. If the pattern has not stabilized, premature abstraction can lock in the wrong design.

Sometimes two pieces of code look similar but solve different problems. In that case, merging them creates a false sense of reuse. The result is a helper that quietly becomes a black box. Developers then spend more time figuring out whether the shared code is safe to change than they would have spent maintaining two explicit copies.

Good reasons to accept repetition

  • Different contexts: the rules are similar but the business meaning is not the same.
  • Low change frequency: the code rarely changes, so duplication has little cost.
  • Early uncertainty: the right abstraction is not yet obvious.
  • Readability first: keeping the code local makes the flow easier to follow.

The practical judgment is simple: if duplication is unlikely to cause inconsistent change, and abstraction would make the code harder to reason about, keep the repetition. DRY should reduce long-term pain, not introduce new confusion in the short term.

That is why experienced teams treat como é o dry as a design question, not a slogan. Use the principle to spot genuine duplication, then decide whether centralization improves the code more than it complicates it.

How Do You Detect and Measure Duplication?

You detect duplication by looking for repeated rules, repeated conditionals, and copied blocks that change for the same reason. Code review is the first line of defense because humans can spot patterns that automated tools miss. Pair programming helps too, especially when two developers independently notice the same logic being reimplemented in separate places.

Static analysis tools can help identify duplicate code structures, but they should not be the only signal. A duplication detector may flag similar syntax even when the business meaning is different. The real question is whether the duplicated code creates a future maintenance problem.

A practical audit workflow

  1. Start with hot spots: inspect files that change often or cause repeated bugs.
  2. Look for copy-paste logic: repeated validation, formatting, and branching are the usual suspects.
  3. Trace the rule: ask what business knowledge the code is representing.
  4. Measure impact: count how many places must change when the rule changes.
  5. Refactor the highest-risk duplicates first: focus on rules that affect users or compliance.

You can also measure duplication indirectly through maintenance pain. If a simple change requires edits in many files, the code probably has too many repeated knowledge points. Bugs that recur in several nearly identical areas are another strong signal.

For technical standards on software quality and structure, the OWASP Code Review Guide is a useful reference when duplicate logic affects security, input handling, or authorization as of July 2026.

What Are the Benefits of Following DRY?

Following DRY gives teams a more maintainable codebase. Centralized logic means fewer places to update, fewer chances to miss a change, and less time spent chasing inconsistencies. That pays off every time product requirements shift or a bug fix needs to move quickly through the system.

Another benefit is better testability. When business logic lives in one place, you can test that single path thoroughly and trust every caller to use the same behavior. That reduces redundant tests and makes failures easier to diagnose.

Key benefits in practice

  • Lower maintenance cost: one edit instead of many.
  • Fewer bugs: fewer opportunities for copies to diverge.
  • Better team productivity: less time spent repeating fixes.
  • Cleaner architecture: more modular, more consistent code.
  • Easier onboarding: new developers find one rule instead of scattered duplicates.

There is also a collaboration benefit. Shared abstractions make team intent visible. If everyone knows where the rule lives, there is less guesswork during reviews, debugging, and handoff work. That becomes even more valuable as codebases and teams grow.

For labor-market context on the ongoing need for maintainable software skills, U.S. Department of Labor workforce resources continue to emphasize skill development and efficient technical work practices as of July 2026.

How Does DRY Apply Across the Stack?

DRY is not just a backend concern. It affects the whole stack, including frontend components, database rules, infrastructure scripts, and configuration management. Anywhere the same knowledge is repeated, the same maintenance risk appears.

On the backend, DRY often means extracting business rules into services or domain objects. On the frontend, it means reusing components and state patterns instead of rebuilding the same UI behavior in multiple views. In infrastructure, it means reducing repeated deployment settings and environment-specific values.

Examples by layer

  • Backend: one order-validation service used by multiple endpoints.
  • Frontend: a shared modal or form component used across screens.
  • Database: constraints or schema rules that enforce data consistency centrally.
  • Configuration: environment-specific values stored outside source code.
  • Deployment: reusable scripts or templates instead of repeated shell logic.

The key is to centralize the right layer, not the nearest layer. Some rules belong in application code, some belong in the database, and some belong in infrastructure templates. Good DRY implementation respects those boundaries instead of flattening everything into one helper file.

For cloud and platform teams, the official documentation from Microsoft Learn and AWS Documentation is useful when centralizing configuration and shared service behavior as of July 2026. If your code touches networking or API design, the IETF RFC Editor is the authoritative source for protocol-level standards.

Key Takeaway

DRY is about repeating knowledge, not just repeating text.

Centralize rules that change together, but keep separate code when the context is different.

Over-abstraction can be worse than duplication if it hides intent.

The best DRY code is easy to change, easy to test, and easy to explain.

FAQ: Common Questions About the DRY Principle

What does DRY mean in simple terms? It means “Don’t Repeat Yourself,” and it tells developers to keep each rule or piece of logic in one place so updates are easier and safer.

Does DRY mean all repeated code must be removed? No. Repetition is acceptable when abstraction would make the code less clear or when the similar code serves different business contexts.

Is DRY the same as reuse? No. Reuse is the mechanism; DRY is the principle that tells you when reuse is worth it. Reuse helps DRY, but not every reuse is a good abstraction.

How does DRY improve code quality? It lowers the chance of inconsistent changes, makes testing more focused, and reduces the maintenance burden that comes from duplicated logic.

When should I allow repetition? Allow repetition when the code is easier to understand as-is, when the pattern is not stable, or when the shared abstraction would become too generic to be useful.

For teams using security and quality frameworks, CIS Controls provide a useful model for reducing avoidable complexity and improving consistency in secure engineering practices as of July 2026.

Conclusion

The DRY principle is one of the simplest ideas in software design, and one of the easiest to get wrong. The goal is not to eliminate every repeated line. The goal is to remove repeated knowledge so a change in one place reliably updates the whole system.

That makes DRY a practical discipline for code quality, maintainability, and team efficiency. Use it to centralize business rules, validation logic, constants, and configuration. Avoid forcing abstractions where they do not help. Good judgment matters more than strict rule-following.

If you want cleaner code, start by looking for duplicate rules, not just duplicate syntax. Review your functions, modules, configs, and UI components for places where one source of truth would make future changes safer. That is the real value of como é o dry: fewer surprises, fewer bugs, and code that is easier to live with over time.

For more practical IT training and software engineering guidance, ITU Online IT Training continues to publish focused content for developers and technical teams who need clear answers, not abstract theory.

Andy Hunt, Dave Thomas, and The Pragmatic Programmer are trademarks or registered trademarks of their respective owners.

[ FAQ ]

Frequently Asked Questions.

What is the main goal of the DRY principle in software development?

O objetivo principal do princípio DRY (Don’t Repeat Yourself) é reduzir a duplicação de código, promovendo uma única fonte de verdade para funcionalidades, regras e constantes. Isso facilita a manutenção, pois qualquer alteração precisa ser feita em um único local, evitando inconsistências.

Ao aplicar o DRY, desenvolvedores evitam a repetição de blocos de código em diferentes partes do projeto. Essa prática melhora a legibilidade do código, diminui erros causados por atualizações não sincronizadas e torna o sistema mais modular e reutilizável.

Quando é apropriado repetir código em um projeto?

Embora o princípio DRY aconselhe evitar a repetição, há situações em que repetir código pode ser benéfico, especialmente se as regras ou contextos forem diferentes. Por exemplo, em casos de pequenas variações que dificultariam uma abstração comum.

Nesses casos, a repetição pode facilitar a compreensão e evitar complexidade desnecessária na implementação. Além disso, quando o código repetido é muito simples ou específico, tentar generalizar pode introduzir mais complexidade do que benefícios reais.

Como posso aplicar o princípio DRY em projetos reais?

Para aplicar o DRY de forma eficaz, comece identificando padrões e duplicações no código. Crie funções, métodos ou classes reutilizáveis que encapsulem regras e constantes comuns, centralizando a lógica.

Utilize técnicas como herança, composição ou templates para evitar duplicação, especialmente em projetos maiores. Além disso, mantenha uma documentação clara para que as mudanças futuras possam ser feitas de forma consistente e eficiente.

Quais são os riscos de não seguir o princípio DRY?

Ignorar o princípio DRY pode levar a múltiplas cópias de código semelhantes, aumentando a complexidade e o esforço de manutenção. Quando uma regra ou validação muda, é necessário atualizar cada local manualmente, aumentando o risco de erros.

Isso também pode causar inconsistências no sistema, dificultando a leitura e compreensão do código por outros desenvolvedores. Eventualmente, esse cenário pode gerar bugs difíceis de rastrear e corrigir, impactando a estabilidade do produto.

Qual a diferença entre reutilização de código e violar o princípio DRY?

A reutilização de código envolve criar componentes ou funções que podem ser usados em diferentes partes do projeto, promovendo eficiência e consistência. Já, a violação do DRY ocorre quando há repetição de lógica semelhante em vários locais sem uma abstração adequada.

Reutilizar código de forma inteligente mantém o princípio DRY intacto, enquanto copiar e colar trechos de código, mesmo que pareçam semelhantes, viola o princípio e pode levar a problemas de manutenção e bugs futuros. A chave está em identificar padrões e criar soluções reutilizáveis e flexíveis.

Related Articles

Ready to start learning? Individual Plans →Team Plans →
Discover More, Learn More
What Is Kerckhoffs's Principle? Learn the fundamentals of Kerckhoffs's Principle to understand how transparent cryptographic systems… What is the Gutenberg Principle? Learn how the Gutenberg Principle enhances page layout to improve readability and… What Is the Open/Close Principle? Discover how applying the Open/Close Principle enables you to extend software functionality… What is the Least Privilege Principle? Learn how the Least Privilege Principle helps minimize access, reduce security risks,… What is the KISS Principle? Discover how applying the KISS principle simplifies design and problem-solving, helping you… What Is (ISC)² CCSP (Certified Cloud Security Professional)? Discover how to enhance your cloud security expertise, prevent common failures, and…
FREE COURSE OFFERS