# Duplicate Code

> The same or similar code appears in multiple places.

- **Category**: Code Smells
- **Subcategory**: Dispensables
- **Canonical URL**: https://designpattern.fyi/patterns/duplicate-code/

---

## Description
'**Intent**: Identify and eliminate code duplication. Duplicated code makes maintenance difficult and increases the risk of inconsistencies.

**Context**: You find identical or very similar code blocks in multiple locations. When bugs are found or requirements change, you must update the same logic in multiple places.

**Solution**: Extract duplicated code into reusable functions, classes, or modules. Apply DRY principle to create single sources of truth for shared logic.'



## Use Cases
Use when you identify identical code blocks, when you make the same changes in multiple files, or when you copy-paste code frequently.



## Implementation Example

```javascript
// Before: Duplicate code
function calculateArea(shape) {
  if (shape.type === 'circle') {
    return Math.PI * shape.radius * shape.radius;
  } else if (shape.type === 'rectangle') {
    return shape.width * shape.height;
  }
}

function calculatePerimeter(shape) {
  if (shape.type === 'circle') {
    return 2 * Math.PI * shape.radius;
  } else if (shape.type === 'rectangle') {
    return 2 * (shape.width + shape.height);
  }
}

// After: Extracted logic
class Circle {
  constructor(radius) {
    this.radius = radius;
  }
  area() {
    return Math.PI * this.radius * this.radius;
  }
  perimeter() {
    return 2 * Math.PI * this.radius;
  }
}

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  area() {
    return this.width * this.height;
  }
  perimeter() {
    return 2 * (this.width + this.height);
  }
}
```



## Trade-offs


### Advantages

- Single source of truth

- Easier maintenance and updates

- Reduced risk of inconsistencies




### Considerations & Drawbacks

- Can lead to over-abstraction

- May require careful parameterization







---
**Reference**: [Original Source](https://refactoring.guru/smells/duplicate-code)

