OPT.IF
Use conditional operator for "if (cond) return; else return;" statements
Description
This rule flags "if(cond)-else" statements that could be replaced with "return (cond ? x : y)".
The conditional operator provides a single expression that yields one of two values based on a boolean expression. The conditional operator results in a more compact expression.
Example
package OPT;
public class IF {
public int method(boolean isDone) {
if (isDone) {
return 0;
} else {
return 10;
}
}
}
Repair
If the "if(cond)-else" statements might return a boolean constant, use "return (cond)" instead.
package OPT;
public class IF {
public int method(boolean isDone) {
return (isDone ? 0 : 10);
}
}
|