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

Cop idea: minimize number of negations in a condition #11399

Open
vlad-pisanov opened this issue Jan 6, 2023 · 1 comment · May be fixed by #11662
Open

Cop idea: minimize number of negations in a condition #11399

vlad-pisanov opened this issue Jan 6, 2023 · 1 comment · May be fixed by #11662

Comments

@vlad-pisanov
Copy link

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)
if x || 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)
if x && y && z && !w

Does this sound reasonable? 🤔

@vlad-pisanov 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
@fatkodima
Copy link
Contributor

I had a similar suggestion a while ago - #8879. Just need to implement 😄

SparLaimor added a commit to SparLaimor/rubocop that referenced this issue Mar 4, 2023
Fixes rubocop#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
```
@SparLaimor SparLaimor linked a pull request Mar 4, 2023 that will close this issue
8 tasks
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 a pull request may close this issue.

2 participants