Skip to content

Merge Comparisons

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-comparisons

Section titled “Sourcery refactoring id: merge-comparisons”

Consolidates multiple comparisons into a single comparison

def process_payment(payment):
if payment.currency == "USD" or payment.currency == "EUR":
process_standard_payment(payment)
else:
process_international_payment(payment)
def process_payment(payment):
if payment.currency in ["USD", "EUR"]:
process_standard_payment(payment)
else:
process_international_payment(payment)

We often have to compare a value to one of several possible others. When written out like the ‘Before’ example we have to look through each comparison to understand it, as well as mentally processing the boolean operator.

By using the in operator and moving the values we are comparing to into a collection we can simplify things.

This has avoided a little bit of duplication, and the conditional can now be taken in and understood with one glance.