SonarLint for Visual Studio 1.2.0 Brings Code Fixes to the IDE
SonarLint for Visual Studio version 1.2.0 was released this week. In this version we focused on improving the user experience by adding code fading and fixes. Code fading makes some issues less obtrusive, and code fixes are concrete suggestions for solving specific issues in the code. This means that when an analyzer identifies an issue in the code, the IDE can propose an automatic fix for it. We’ve added fixes for 17 rules, and the best part is that the user can choose to fix all issues of the same type all at once for the whole solution, which can immensely speed up paying down technical debt.
Analyzers and code fixes are integrated into Visual Studio 2015 natively thanks to Roslyn. As you would expect, the issues we raise show up in the Error Window. As part of improving the user experience, now some issues on redundancies or useless code just show up as faded text (note the fading in the image below). So these less serious issues aren’t uselessly cluttering the Error Window any more.
Redundancies fall into the “easy to fix automatically” category. For example, for the above issue (Rule S3254) we could simply remove the redundant code. In Visual Studio, to check and accept the proposed code fix, you should hover over the issue location and expand the lightbulb tooltip. Or you can move the caret to the line of the issue, and hit Ctrl+. (There is a good video on Channel9, which shows the navigational shortcuts in Visual Studio 2015.) The tooltip window contains all the available options for the issue. There can be multiple possible fixes for an error, so you can choose which one to apply. For the above case, there is only one fix, which is to remove the redundant arguments. Also note in the image below that at the bottom of the preview window you can choose to apply this fix to all issues in the document/project/solution.
One of my favorite code fixes is the one that simplifies conditional statements. Consider the following code, where the
false branches of the conditional statement are very similar.
Here, the code fix for Rule S3240 proposes using the
?? (null-coalescing) operator instead of the 8-line conditional statement. The code fix provider is clever enough to recognize that this
if can be simplified to
?? and not just to the
?: (ternary) operator, and it only proposes the simpler one.
These are just two of the new code fixes. There are 16 more available (one rule has two fixes). We also added two new rules and fixed some bugs in this version. You can see the full list of rules at the new version-specific landing page. A slight restructuring of the SonarLint website, means that each release now has its own landing page, which summarizes the changes since the previous version.