public class AvoidConstantAsFirstOperandInConditionCheck
extends com.puppycrawl.tools.checkstyle.api.AbstractCheck
If comparing values, C(C++) developers prefer to put the constant first in the equality check,
to prevent situations of assignment rather than equality checking. It is easy to write "="
instead of "==", and no compile error will be produced but condition will work in a different
way then intended. However, in Java it is impossible to use assignment inside the
if condition, so that habit becomes unnecessary and does damage to the readability
of the code.
This check was extended to include all equality checks like ">", ">=", "<", "<=" for users who prefer constants always be on the right-hand side for any condition.
Example:
if (null == variable)
rather than
if (variable == null)
because if you forget one (typo mistake) of the equal sign, you end up with
if (variable = null)
which assigns null to variable and IF always evaluate to true.
| Modifier and Type | Field and Description |
|---|---|
static String |
MSG_KEY
A key is pointing to the warning message text in "messages.properties"
file.
|
| Constructor and Description |
|---|
AvoidConstantAsFirstOperandInConditionCheck() |
| Modifier and Type | Method and Description |
|---|---|
int[] |
getAcceptableTokens() |
int[] |
getDefaultTokens() |
int[] |
getRequiredTokens() |
void |
setTargetConstantTypes(String... targets)
Set target constant types.
|
void |
visitToken(com.puppycrawl.tools.checkstyle.api.DetailAST detailAST) |
beginTree, clearMessages, destroy, finishTree, getFileContents, getLine, getLines, getMessages, getTabWidth, getTokenNames, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeveritypublic static final String MSG_KEY
public AvoidConstantAsFirstOperandInConditionCheck()
public void setTargetConstantTypes(String... targets)
targets - target constant typespublic int[] getDefaultTokens()
getDefaultTokens in class com.puppycrawl.tools.checkstyle.api.AbstractCheckpublic int[] getAcceptableTokens()
getAcceptableTokens in class com.puppycrawl.tools.checkstyle.api.AbstractCheckpublic int[] getRequiredTokens()
getRequiredTokens in class com.puppycrawl.tools.checkstyle.api.AbstractCheckpublic void visitToken(com.puppycrawl.tools.checkstyle.api.DetailAST detailAST)
visitToken in class com.puppycrawl.tools.checkstyle.api.AbstractCheckCopyright © 2021. All rights reserved.