Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new Style/NegatedIfElseCondition cop #8967

Merged
merged 1 commit into from Oct 31, 2020

Conversation

fatkodima
Copy link
Contributor

@fatkodima fatkodima commented Oct 29, 2020

This cop checks for uses of if-else and ternary operators with a negated condition which can be simplified by inverting condition and swapping branches.

# bad
if !x
  do_something
else
  do_something_else
end

# good
if x
  do_something_else
else
  do_something
end
      
# bad
!x ? do_something : do_something_else

# good
x ? do_something_else : do_something

# bad 
if x != y
  do_something
else
  do_something_else
end

# good
if x == y
  do_something_else
else
  do_something
end

I'm sure, there is a better name for this cop.

class InvertedIfElse < Base
extend AutoCorrector

MSG = 'Invert the negative condition and swap branches.'
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

negative -> negated

and what the conditional's branches (or something like this)

@bbatsov
Copy link
Collaborator

bbatsov commented Oct 30, 2020

Nicely done! I only had a tiny bit of feedback about the message. I'm also thinking a better name for the cop might be "NegatedIfElseCondition".

@fatkodima fatkodima changed the title Add new Style/InvertedIfElse cop Add new Style/NegatedIfElseCondition cop Oct 30, 2020
@fatkodima
Copy link
Contributor Author

Changed the cop name and offense message.

@bbatsov bbatsov merged commit 679f02c into rubocop:master Oct 31, 2020
@bbatsov
Copy link
Collaborator

bbatsov commented Oct 31, 2020

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants