# Code Smell 232 - Reusable Code

*Don't Repeat Yourself. Don't Repeat Yourself*

> TL;DR: You can find missing abstractions by looking at repeated code

# Problems

- DRY principle violation

- Maintainability

- Ripple Effect

# Solutions

1. Create the repeated code

2. Introduce an abstraction

3. Replace the references and point to the new abstraction

4. Remove the duplication

# Context

Repeated code is a symptom of missing abstractions. 

This is natural in the learning process since we cannot foresee those abstractions.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/b1380b6b9850ec6f12c14bfeebbfc505)
```python
def calculate_area(length, width):
    return length * width

def calculate_volume(length, width, height):
    return length * width * height
``` 

## Right

[Gist Url]: # (https://gist.github.com/mcsee/582e44a1004c102199039c5961f32ceb)
```python
def calculate_area(length, width):
    return length * width

def calculate_volume(length, width, height):
    base_area = calculate_area(length, width)
    return base_area * height
``` 

# Detection

[X] Semi-Automatic

Some linters can find repeated code patterns.

# Exceptions

The abstraction must have a dependency correspondence on the [Bijection](https://maximilianocontieri.com/the-one-and-only-software-design-principle) 

# Tags

- Bloaters

# Conclusion

Repeated code is a problem and a hint for a missing abstraction.

Remember you *don't need to avoid* copying and pasting.

You must explicitly *write* the repeated code and remove the duplication by introducing an abstraction.

Avoiding the cut and paste is a shortcut and a symptom of premature optimization.

# Relations

%[https://maximilianocontieri.com/code-smell-46-repeated-code]

%[https://maximilianocontieri.com/code-smell-182-over-generalization]

# Disclaimer

Code Smells are my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Mitchell Griest](https://unsplash.com/@griestprojects) on [Unsplash](https://unsplash.com/photos/person-showing-assorted-color-bags-psDzkLlifxQ)
  
---
 
> Pasting code from the internet into production code is like chewing gum found in the street.

_Mike Johnson_

%[https://maximilianocontieri.com/software-engineering-great-quotes] 

---

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
