org.codenarc.rule.basic
Class UnnecessaryTernaryExpressionRule
java.lang.Object
org.codenarc.rule.AbstractRule
org.codenarc.rule.AbstractAstVisitorRule
org.codenarc.rule.basic.UnnecessaryTernaryExpressionRule
class UnnecessaryTernaryExpressionRule
extends AbstractAstVisitorRule
Rule that checks for ternary expressions where the conditional expression always evaluates to
a boolean and the true and false expressions are merely returning true
and
false
constants. These cases can be replaced by a simple boolean expression.
Examples include:
boolean result = x==99 ? true : false
- can be replaced by boolean result = x==99
boolean result = x && y ? true : false
- can be replaced by boolean result = x && y
def result = x||y ? false : true
- can be replaced by def result = !(x||y)
boolean result = x >= 1 ? true: false
- can be replaced by boolean result = x >= 1
boolean result = x < 99 ? Boolean.TRUE : Boolean.FALSE
- can be replaced by boolean result = x < 99
def result = !x ? true : false
- can be replaced by def result = !x
The rule also checks for ternary expressions where the true and false expressions are the same constant or
variable expression. Examples include:
def result = x ? '123' : '123'
- can be replaced by def result = '123'
def result = x ? null : null
- can be replaced by def result = null
def result = x ? 23 : 23
- can be replaced by def result = 23
def result = x ? MAX_VALUE : MAX_VALUE
- can be replaced by def result = MAX_VALUE
- author:
- Chris Mair
- version:
- $Revision: 346 $ - $Date: 2010-05-08 22:13:44 -0400 (Sat, 08 May 2010) $
Methods inherited from class AbstractRule
|
applyTo, createViolation, createViolation, createViolationForImport, createViolationForImport, getImportsSortedByLineNumber, getName, getPriority, packageNameForImport, setName, setPriority, sourceLineAndNumberForImport, sourceLineAndNumberForImport |
astVisitorClass
Class astVisitorClass
-
name
String name
-
priority
int priority
-
UnnecessaryTernaryExpressionRule
UnnecessaryTernaryExpressionRule()
-
Groovy Documentation