söndag 28 januari 2018

Two subtle Linq-related bugs that ReSharper highlighted during code review

ReSharper, a productivity tool that helps you automate some of the code writing and also analyses the code written. The biggest drawback I find with it is that it makes the Visual Studio startup a lot slower. Yes, that is annoying, but I still value the code quality help it gives me more than a fast startup.

This is two examples of Linq-related bugs that ReSharper pointed out for me when I was reviewing code. I hope I would have found the bugs anyway, but Resharper made it a no-brainer to find them and almost impossible to miss.
The examples do not show the original code, only the same problems.
The code writers did not use ReSharper.

Example 1

This is example 1, without the help of ReSharper, do you see the problem?

This is the same code, but with ReSharper active, the problem is shown more clearly, isn't it?


The gray code in the if-block tells us that the code isn't used. Ok, so why isn't it used? Hoover over the blue squiggly-lined code and you will see:



Expression is always false. This hopefully makes a programmer with little experience in Linq to do some research to find out why. And then change the if-condition
projects == null 
to 
projects.Count == 0 
or 
!projects.Any()

Because Linq's ToList() does never return null, if no rows are matched an empty list is returned.

Example 2

This is a similar problem, do you see what the problem is this time?


With ReSharper activated it looks like this again, but not for the same reason.


The variable projects is not the resulting list of the query. It IS the query. A query that hasn't been executed. And therefore, since it is a query (or an IQueryable object) that is assigned to a value during creation, it cannot be null when the execution of the code reaches the if-condition.


Conclusions

These two bugs can to a code writer or reviewer be rather subtle, but with the help of ReSharper they are not so subtle. Subtle bugs can easily go under the review radar and if the code isn't tested thoroughly it can even reach production. And bugs having come that far are often more cumbersome/expensive to fix than if they had been caught earlier in the process.
That's why I find ReSharper worth its price, both when it comes to money and performance.

Inga kommentarer:

Skicka en kommentar