You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently, Style/NegatedIf (and Style/NegatedUnless) recommend if x over unless !x, which is good because negations are less natural for the reader.
What might be useful is a cop that goes a step further and recommends if x || y over unless !x && !y. That is, a cop that reduces the number of negations in a boolean expression as much as possible by leveraging DeMorgan's Rule.
In its basic form, it could look for conjunctions (or disjunctions) where all terms are negated:
# bad (all terms negated)unless !x && !y && !z# good (all terms positive)ifx || y || z
A more complex version could look for conjunctions (or disjunctions) where there are more negations than positives:
# bad (3 negations, 1 positive)unless !x || !y || !z || w# good (3 positives, 1 negation)ifx && y && z && !w
Does this sound reasonable? 🤔
The text was updated successfully, but these errors were encountered:
vlad-pisanov
changed the title
Cop idea: reduce number of negations in a condition
Cop idea: minimize number of negations in a condition
Jan 6, 2023
Fixesrubocop#11399.
This PR adds new `Style/UnlessMinimizeNegations` cop.
It minimizes the number of negations in an `unless` using De Morgan’s laws.
```ruby
# bad (all terms negated)
do_something unless !x && !y
# good (all terms positive)
do_something if x || y
# bad (2 negations, 1 positive)
do_something unless !x || !y || z
# good (2 positives, 1 negation)
do_something if x && y && !z
```
Currently,
Style/NegatedIf
(andStyle/NegatedUnless
) recommendif x
overunless !x
, which is good because negations are less natural for the reader.What might be useful is a cop that goes a step further and recommends
if x || y
overunless !x && !y
. That is, a cop that reduces the number of negations in a boolean expression as much as possible by leveraging DeMorgan's Rule.In its basic form, it could look for conjunctions (or disjunctions) where all terms are negated:
A more complex version could look for conjunctions (or disjunctions) where there are more negations than positives:
Does this sound reasonable? 🤔
The text was updated successfully, but these errors were encountered: