Duplicate Code refers to instances where identical or very similar code appears multiple times in a program. It is considered a bad practice because it can lead to issues with maintainability, readability, and error-proneness.
1. Exact Duplicates: Code that is completely identical. This often happens when developers copy and paste the same code in different locations.
Example:
def calculate_area_circle(radius):
return 3.14 * radius * radius
def calculate_area_sphere(radius):
return 3.14 * radius * radius # Identical code
2. Structural Duplicates: Code that is not exactly the same but has similar structure and functionality, with minor differences such as variable names.
Example:
def calculate_area_circle(radius):
return 3.14 * radius * radius
def calculate_area_square(side):
return side * side # Similar structure
3. Logical Duplicates: Code that performs the same task but is written differently.
Example:
def calculate_area_circle(radius):
return 3.14 * radius ** 2
def calculate_area_circle_alt(radius):
return 3.14 * radius * radius # Same logic, different style
1. Refactoring: Extract similar or identical code into a shared function or method.
Example:
def calculate_area(shape, dimension):
if shape == 'circle':
return 3.14 * dimension * dimension
elif shape == 'square':
return dimension * dimension
2. Modularization: Use functions and classes to reduce repetition.
3. Apply the DRY Principle: "Don't Repeat Yourself" – avoid duplicating information or logic in your code.
4. Use Tools: Tools like SonarQube or CodeClimate can automatically detect duplicate code.
Reducing duplicate code improves code quality, simplifies maintenance, and minimizes the risk of bugs in the software.