sourcery-ai / sourcery

Instant AI code reviews
https://sourcery.ai
MIT License
1.53k stars 66 forks source link

New refactoring suggestion to shorten duplicate equality expressions #244

Open diceroll123 opened 2 years ago

diceroll123 commented 2 years ago

Issue description or question

Before this currently-unmade refactoring:

name = 'blah'
random_name = 'asdf'
other_random_name = 'sdfg'

if random_name == name or other_random_name == name:
    print('aaaa')

After:

name = 'blah'
random_name = 'asdf'
other_random_name = 'sdfg'

if name in (random_name, other_random_name):
    print('aaaa')

There's a lot of variability that could come from this, simplifying run-on if statements as well.

I understand the somewhat negligible performance cost to running the after code vs. the before code, but I leave it up to the Sourcery team to decide if it's worth!

Thanks for readin'.

Sourcery Version

v0.11.5

Code editor or IDE name and version

VSCode Version: 1.67.2 (user setup) Commit: c3511e6c69bb39013c4a4b7b9566ec1ca73fc4d5 Date: 2022-05-17T18:15:52.058Z Electron: 17.4.1 Chromium: 98.0.4758.141 Node.js: 16.13.0 V8: 9.8.177.13-electron.0 OS: Windows_NT x64 10.0.25120

ruancomelli commented 2 years ago

Hi @diceroll123! Nice catch!

This is actually merge-comparisons, but it seems that Sourcery is not happy with the fact that the repeated variable (name) is on the right-hand side of the comparisons.

If you re-order your equality comparisons so that name is on the left, this refactoring gets triggered:

name = 'blah'
random_name = 'asdf'
other_random_name = 'sdfg'

if name == random_name or name == other_random_name: # Sourcery - Replace multiple comparisons of same variable with `in` operator
    print('aaaa')

But you're correct, Sourcery should refactor your snippet as well regardless of ordering - I'll add this to our pipeline. Thanks!