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(s) Idea: remove redundant booleans from control flow #12840
Comments
1. Boolean as antecedent of a conditional (
|
Note two of your examples are not strictly equivalent (assuming you don't literally mean a string # Bad
anything || true
# Good
true In the first case # Bad
foo || true || bar
# Good
true In the first case |
2 > 1 ? foo : bar Although this is easy to see that it is always true, it is not easy to detect via static analysis as the clause (or any other code) is not evaluated and there are many forms it could take. |
Sounds like an extension of Lint/LiteralAsCondition which already covers many of these cases: false ? foo : bar
# W: Lint/LiteralAsCondition: Literal false appeared as a condition.
if false
"a"
elsif bar
"b"
else
"c"
end
# W: Lint/LiteralAsCondition: Literal false appeared as a condition. |
Is your feature request related to a problem? Please describe.
Basic problem & use case
It is possible to run across cases where there are booleans in the antecedents of conditionals (
true ? foo : bar
). This kind of case can be simplified to return the logical branch that the statement will always results in (foo
). A cop that could take care of this might be calledLint/BooleanCondition
.Perhaps sometimes a well-intentioned developer could straightforwardly make this kind of mistake. Anyway, another use case in production code is with what my team calls "fully-enabled feature flags": a bit of conditional code that will forever more evaluate to
true
, which we can reasonablygsub
to justtrue
. If we hadLint/BooleanCondition
cop, then we could automate the feature flags away:Similar cases
antecendents that always evaluate to true
Sometimes a conditional can have an antecedent that will always evaluate to true, especially when it contains no variables, e.g.
2 > 1 ? foo : bar
, which will always evaluate tofoo
. Perhaps that kind of case could also be taken care of by aLint/BooleanCondition
cop.conjunctions and disjunctions
true && foo
will always evaluate tofoo
.true || foo
will always evaluate totrue
. Perhaps such cases should also fit into the scope ofLint/BooleanCondition
. If not, then those cases could have their own cops,Lint/BooleanInConjunction
andLint/BooleanInDisjucntion
.unless
,case
, etc.Perhaps it goes without saying, but we would want
Lint/BooleanCondition
to handle the various kinds of conditionals Ruby allows for, includingif
, the ternary operator,unless
,case
, and possiblyand
andor
.Describe the solution you'd like
A solution that could auto-correct away such cases as I will post in the first comment.
The text was updated successfully, but these errors were encountered: