# Duplicated code

> A code smell.

A [code smell](https://wiki.g15e.com/en/pages/Code%20smell.txt).

## The Cost of Duplicate Code

Read multiple times, edit multiple times:

> Duplication means that every time you read these copies, you need to read them carefully to see if there's any difference. If you need to change the duplicated code, you have to find and catch each duplication. --Chapter 3, [Refactoring: Improving the design of existing code](https://wiki.g15e.com/en/pages/Refactoring%20-%20Improving%20the%20design%20of%20existing%20code.txt)

If you always know where the duplication is, there are fewer problems. There is duplicate code, but as soon as you fix one code and don't fix the rest because you don't know it's duplicated, a bug or inconsistency in operation occurs. These problems are usually not discovered until much later, so the cost of fixing them is high ([Defect cost increase](https://wiki.g15e.com/en/pages/Defect%20cost%20increase.txt)).

## Small duplications

It is important not to miss even the smallest or unclear duplications. This can cause bugs in the future.

## Coincidence

The same literal, same expression, etc. are not necessarily duplicates. It could be a coincidence. Treat them as duplicates only when changing one necessarily requires changing the other.

## Related refactoring

- <Extract function>
- <Slide statements>
- <Pull up method>

## Other helpful perspectives

Use duplication to discover missing design elements:

> Duplication is always a bad thing, unless you look at it as motivation to find the missing design element. --Chapter 23, [Test-driven development: by example](https://wiki.g15e.com/en/pages/Test-driven%20development%20-%20By%20example.txt)

Intentionally creating a duplicate: [Reconcile differences](https://wiki.g15e.com/en/pages/Reconcile%20differences.txt)

## See also

- [Dependency and duplication](https://wiki.g15e.com/pages/Dependency%20and%20duplication.txt)