Why Netbeans suggests improving the for?

5

When you were doing this for Netbeans showed that bulb tips to improve the code in the for line. The suggestion was to reverse the condition. Here is the code:

Before improvement:

for(int j = 0; j < selectionPaths.length; j++) {
   if( isDescendant(selectionPaths[j], path) )
      return true;
}

After of the improvement suggested by Netbeans:

for(int j = 0; selectionPaths.length >= j; j++) {
   if( isDescendant(selectionPaths[j], path) )
      return true;
}

Update: After the "improvement" the program throws the ArrayIndexOutOfBoundsException exception.

But then why did Netbeans give this suggestion if after accepting it the program gives error? Is there a specific reason or only issue of code convention? Or is it a Netbeans fault?

Note: The Netbeans version is 8.0.1. The suggestion appears when the cursor is positioned in the condition, more precisely in the variable selectionPaths .

    
asked by anonymous 31.10.2014 / 11:07

2 answers

2

Netbeans parses only the code, not the context in which it is inserted, ie if your code can be refactored, it will give you a suggestion, however it will not check all of your code to suggest a refactoring " decent". Therefore it is the choice of the programmer to accept or not the choice of the IDE.

If you accept any suggestion from the IDE, keep in mind that a code reset will be necessary for it to be plausible to operate. In other words, in 70% of cases NetBeans gives some good suggestions, but in the other 30% it says some nonsense things that will depend on the programmer's experience to work.

As has already been said in the comments, this is the subject of a discussion about tastes, there are people who prefer codes in one way and people who prefer otherwise, it's the same thing as having:

If() {

}

and

if()
{

}

Go for it.

    
31.10.2014 / 12:55
0

In this specific case it is a question of good practices and conventions.

Ex:

In the way you have done j < selectionPaths.length; if by carelessness putting the = sign instead of < you would be assigning selectionPaths.length to j .

The suggested example selectionPaths.length >= j also assigns in javascript but in other languages or if selectionPaths.length is a method ( selectionPaths.length() ) and if it were wrong to put = instead of >= , a syntax being therefore easier to identify than a logic error of that level.

    
31.10.2014 / 13:48