if/else returning a boolean literal from each branch
ID |
apex.maintainability.simplify_boolean_expression |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Readability |
Language |
Apex |
Description
Reports an if/else that returns true from one branch and false from the other, where the condition itself is the value being returned.
Rationale
Four lines and a branch say what one line says: the condition already is the answer. The branching form also invites a later edit to change one side and not the other, which turns a tautology into an inverted result that reads as if it were deliberate. Returning the condition is safe here because the if has already evaluated it, so no null can survive to the return.
The following code illustrates the pattern detected by this rule:
public class SimplifyBoolean {
public Boolean positive(Integer a) {
// FLAGGED: if/else returning a boolean literal from each branch
if (a > 0) { return true; } else { return false; }
}
public Boolean negative(Integer a) {
// FLAGGED: if/else returning a boolean literal from each branch
if (a > 0) { return false; } else { return true; }
}
public Boolean direct(Integer a) {
return a > 0;
}
public Boolean nullSafe(Map<String, Boolean> flags) {
if (flags.get('active') == true) {
return true;
}
return false;
}
}