Remove Repeated Code
Duplicated code is widespread on large codebases. Duplication damages readability and introduces the risk of inconsistencies and bugs. Here, I discuss two ways of refactoring repeated code.
Identifying Repeated Code
First, you need to identify the duplicated code snippets within the codebase before addressing it.
Common signs of duplicated code include identical or nearly identical sections appearing in multiple places due to copying and pasting, similar functions or methods that perform comparable operations but differ slightly in implementation, and shared logic or algorithms replicated across different parts of the codebase.
Extract Method Refactoring
The Extract Method/Function refactoring technique involves identifying a cohesive block of code and moving it into its function or method. This allows the code to be reused wherever necessary, reducing duplication.
Consider the following Python code that generates sales reports:
def generate_sales_report(data): total_sales = 0 for item in data: total_sales += item['price'] * item['quantity'] tax = total_sales * 0.07 report = f"Sales Report\nTotal Sales: ${total_sales:.2f}\nTax: ${tax:.2f}" return report
You also have another function displaying inventory reports:
def generate_inventory_report(data): total_value = 0 for item in data: total_value += item['price'] * item['quantity'] tax = total_value * 0.07 report = f"Inventory Report\nTotal Value: ...
Get Remove Repeated Code now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.