Code Smells ♨️– Duplicated Code

Martin Jurran
Software Design Patterns
2 min readFeb 8, 2024

Duplicated code is one of the worst, but easiest to find smells. It makes it harder for people to read your program. It also takes longer for developers to check if the code is exactly the same. This wastes time that could be spent on other parts of the program.

“Copy and paste is a dangerous practice, a pervasive source of smells in software development and a leading cause of defects in industrial systems. Duplicated code, in particular, can complicate software maintenance, reduce maintainability, and increase overall software development costs. It is, therefore, critical to detect, track, and remove duplicated code as early as possible in the software development life cycle.” — Yuanyuan Zhang and Yanhong A. Liu (2018)

When you change the code, you have to make sure you change it in all the copies, which can be hard and time-consuming.

Causation

Duplicated Code is usually be due to developers not properly communicating or collaborating with each other.

For instance, consider a situation where two developers in a software development team are working on different parts of a system. In the absence of proper communication among themselves, both developers might end up writing code that performs the same functionality. In such cases, instead of reusing the existing code of another developer, the developer might end up duplicating this code.

Such a situation can be common if there is no code-review mechanism in place or if there is no centralized code repository available for all developers to review.

Over time, this duplicated code can accumulate, making the codebase bloated, inconsistent, hard to maintain, and introducing more potential points of failure. Therefore, it is essential that developers communicate effectively and work collaboratively to minimize duplicated code and ensure that only one copy of the code exists in the codebase, reducing complexity and increasing maintainability.

Example

Smelly

public class Program {   
int GetSquare(int num) {
return num * num;
}

int GetCube(int num) {
return num * num * num;
}
}

Solution

public class Program {
int GetSquare(int num) {
return _GetPower(num, 2);
}

int GetCube(int num) {
return _GetPower(num, 3);
}

private int _GetPower(int num, int exponent) {
int result = num;
for (int i = 1; i < exponent; i++) {
result *= num;
}
return result;
}
}

Refactoring

Extract Class

Extract Function

Pull Up Method

Slide Statement

Form Template Method

--

--

Martin Jurran
Software Design Patterns

Software Engineer | Future-proof solutions through strategic consulting and software engineering | Azure DevOps, C#/.NET, JavaScript