Java Rule - double if block instead of elseif

java
(Darren Hartford) #1

Hi everyone,
First topic entry, be gentle :slight_smile:

Is there an existing Java rule that may be by default turned off to deal with double if blocks that use the same parameters but checked differently, instead of alternatively using ‘else if’?

Example:

if(name == null){
  return "hello person!";
}

if(name != null){
  return "hello " + name;  
}

Recommended correction:

if(name == null){
  return "hello person!";
}else if(name != null){
  return "hello " + name;  
}

Additional Constraints:

If there is additional code in between two if blocks with the same parameters, this rule should not trigger by default. Comments in between two if blocks…open to suggestion, my opinion is to still trigger.

(Michael Gumowski) #2

Hey @dhartford,

Welcome in this forum. Sorry, I somehow missed your thread (weeks ago…) while looking at new topics targeting Java (it wasn’t using the tags and I’m not reading all the threads).

I searched a bit in our existing rules, and could not match one matching to your requirements.
I know that it’s an example, but note that in snippet I would expect the rule “Condition always True” to trigger on the second condition (you don’t have the choice regarding nullness).

In a way, I feel that what you suggest would be close from what rule squid:S1066 (Collapsible “if” statements should be merged) is already doing… But it’s not really the same use case.

I’m however wondering, while your example is quite simple, what would you expect when having more complex conditions?

if (a && b) {
 // ...
}

if (b || (c && a)) {
  // ...
}

I however agree that as soon as there is code in between the two if, we can’t say anything. Would you expect the rule to only trigger for simplest cases (single variable, with multiple states)?

Finally, I’m also wondering what would be the ultimate goal of such rule. Question of style? Grouping tests on same variables together? Some would argue that it’s not necessarily “easier to read”, and I would appreciate your opinion! :slight_smile:

Cheers,
Michael