Merge Comparisons¶
Sourcery refactoring id: merge-comparisons
¶
Description:¶
Consolidates multiple comparisons into a single comparison
Before:¶
def process_payment(payment):
if payment.currency == "USD" or payment.currency == "EUR":
process_standard_payment(payment)
else:
process_international_payment(payment)
After:¶
def process_payment(payment):
if payment.currency in ["USD", "EUR"]:
process_standard_payment(payment)
else:
process_international_payment(payment)
Explanation:¶
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.