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
[java] ConfusingTernary should treat != null as positive condition #278
Comments
@sebbASF thanks for the report! I think there are a bunch of things to think about on this most interesting report. Firstly, regardless of all else, the rule is certainly just introducing noise. The rule attempts to avoid "inverted" conditionals such as "if NOT A then B else C", but on this scenario, all checks are for different things altogether. The rule should not apply to this block. Right now, there is a Then it's the point of considering "!=" a positive. That would allow to write code such as: if (x != null) {
return x.foo();
} else {
return 0;
} which is the very kind of code this rule attempts to prevent. What I guess should happen is:
|
My example happened to use the same variable, but there are other cases such as a hierarchy of defaults where the conditions need to check for the first non-null variable. My point is that null is special here, because the natural check for non-null uses inequality. |
I'm having the same issue: if (deepLink.getQueryParameter(TEAM_QUERY_KEY) != null) { // PMD shouldn't report this as an error
launchTeam(getTeam(deepLink).get(0));
} else if (deepLink.toString().equals(ADD_SCOUT_INTENT)) {
NewTeamDialog.show(mActivity.getSupportFragmentManager());
} |
@SUPERCILEX yeap, similar case, you are analyzing different values on the ifs (all related to |
I think that any usage of In other words, I think |
I think the point is only to consider if (x != 2) {
//...
} else {
//...
} But null checks will be ignored because it's (arguably) as easy to read |
Yes; see the title and initial comment of this issue. |
Any updates on this ? |
I would also agree that a null check is a special case that needs to be treated differently. The following structure:
is much more confusing to read than
Currently I’m using the following workaround: if (Objects.nonNull(something)) {
// do the thing with something
} else {
// do the fallback
} However, this might have some runtime overhead (I’m not sure if the compiler inlines it, though). |
Is this being considered? Any update? |
Rule Set: ConfusingTernary
Description:
ConfusingTernary should treat negative comparisons with null as a positive condtion.
The condition "!= null" is often used to mean "the item is present" rather than "the item is not absent".
Rewriting using "== null" would make the code much harder to follow.
Code Sample demonstrating the issue:
Running PMD through: Ant
The text was updated successfully, but these errors were encountered: