# Don't Repeat Yourself (DRY)

> Every piece of knowledge must have a single, unambiguous representation within a system.

- **Category**: Dry Yagni
- **Subcategory**: principles
- **Canonical URL**: https://designpattern.fyi/patterns/dry/

---

## Description
'**Intent**: Avoid duplication of logic and data. Every piece of knowledge should have a single, authoritative representation in the system.

**Context**: You find yourself copying and pasting code, writing similar functions with slight variations, or maintaining the same logic in multiple places. When bugs are found, you have to fix them in multiple locations.

**Solution**: Identify repeated code and extract it into reusable functions, classes, or modules. Create abstractions that capture the common logic and parameterize the differences.'



## Use Cases
Use when you identify duplicated code, when you need to make similar changes in multiple places, or when you want to reduce maintenance burden.



## Implementation Example

```javascript
// Before: Duplicated code
function calculateCircleArea(radius) {
  return Math.PI * radius * radius;
}

function calculateSphereVolume(radius) {
  return (4/3) * Math.PI * radius * radius * radius;
}

function calculateCylinderVolume(radius, height) {
  return Math.PI * radius * radius * height;
}

// After: DRY applied
function calculatePIRadiusSquared(radius) {
  return Math.PI * radius * radius;
}

function calculateCircleArea(radius) {
  return calculatePIRadiusSquared(radius);
}

function calculateSphereVolume(radius) {
  return (4/3) * calculatePIRadiusSquared(radius) * radius;
}

function calculateCylinderVolume(radius, height) {
  return calculatePIRadiusSquared(radius) * height;
}
```



## Trade-offs


### Advantages

- Reduced code duplication

- Easier maintenance and updates

- Consistent behavior across codebase

- Reduced risk of inconsistencies




### Considerations & Drawbacks

- Can lead to over-abstraction

- May increase complexity for simple cases

- Premature extraction can create rigid code







