Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnnecessaryLocalBeforeReturn - why it's bad?

Tags:

pmd

I started my adventure with Sonar ;)

Sonar with it's default configuration has PMD UnnecessaryLocalBeforeReturn error set on major level.

    List<Todo> filtered = em.createQuery(query).getResultList();
    return filtered;

It means for me that I should change this code above in one line.

It's really interesting for me because I recommend my colleagues to make this "unnecessary" local before return.

I think it ease debugging. When I set up breakpoint on return line, I'm sure that when I get there this value will be ready and I don't have to make selection over my statement or do "Step over Expression".

Beside I believe it has positive impact on reducing return points in methods.

My question is: Are there some kind of explanations/discussions why errors from projects such as Checkstyle, PMD, FindBugs, etc. were acknowledged as errors?

like image 338
zimi Avatar asked Sep 23 '13 13:09

zimi


People also ask

Why should you try and avoid using unnecessary variables?

They can be powerful if used properly, but they can also point to a lack of proper design when not used in the correct way. It's a particularly bad practice when variables are used to explain what is going on in the code. It's no different than the issue of comments.

Are local variables bad?

Local Variables are WeirdThat makes your local code behave differently than your stored procedure. It's frustrating and confusing. It can lead you to create the wrong indexes, resort to index hints, or start using RECOMPILE hints everywhere.

Is it good idea to return an address or a reference of a local variable?

The return statement should not return a pointer that has the address of a local variable ( sum ) because, as soon as the function exits, all local variables are destroyed and your pointer will be pointing to someplace in the memory that you no longer own.

Why it is considered to be good practice to use local variables?

So, by using a local variable you decrease the dependencies between your components, i.e. you decrease the complexity of your code. You should only use global variable when you really need to share data, but each variable should always be visible in the smallest scope possible.


1 Answers

If your point is only viewing the content of the List, you may just as well either put the break point in the caller of the method. The other option is to put a break point and evaluate the value (Eclipse & IntelliJ do it nicely).

Why is it consedered as a bad practice ?

You just add a reference to a variable while it is not necessary.

This just increase the workload on the Garbage Collector.

like image 99
tsmets Avatar answered Oct 13 '22 22:10

tsmets