Skip to content

Merge Duplicate Blocks

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

Sourcery refactoring id: merge-duplicate-blocks

Section titled “Sourcery refactoring id: merge-duplicate-blocks”

Restructure conditional to merge duplicate branches together

def process_payment(payment):
if payment.currency == "USD":
process_standard_payment(payment)
elif payment.currency == "EUR":
process_standard_payment(payment)
else:
process_international_payment(payment)
def process_payment(payment):
if payment.currency == "USD" or payment.currency == "EUR":
process_standard_payment(payment)
else:
process_international_payment(payment)

We should always be searching out opportunities to remove duplicated code. A good place to do so is where there are multiple identical blocks inside an if..elif chain. This refactoring combines such blocks.

Now if we need to change the process_standard_payment(payment) line we can do it in one place instead of two. This becomes even more important if these blocks involve multiple lines.