What is Sonarlint and How it works? An Overview and Its Use Cases

History & Origin of Sonarlint

More than your average linting tool

Your current linting tools may come with overhead – specialized tools for languages or longer setup and config time. With SonarLint, you can settle on a single solution to address your Code Quality and Code Security issues. We have you covered with hundreds of unique, language-specific rules to catch Bugs, Code Smells, and Security Vulnerabilities right in the IDE, as you code.

What is  Sonarlint

SonarLint enables you to code better with on-the-fly analysis and support for hundreds of deep static analysis rules to detect common mistakes, tricky bugs, and security issues.

eal-time feedback as you code

Your IDE is the best place to catch coding issues. SonarLint enables you to code better with on-the-fly analysis and support for hundreds of deep static analysis rules to detect common mistakes, tricky bugs, and security issues.

easy to use, no configuration required

Get maximum coverage for your programming language with no installation overhead or lengthy setup. Just install the plugin and continue to code while SonarLint assists you in the background. It’s the only in-IDE solution you’ll ever need.

How Sonarlint works aka Sonarlint architecture?

SonarLint in IntelliJ. The SonarLint IntelliJ plug-in allows you to see an easy report about code issues right inside IntelliJ. It runs an immediate analysis as you change code, and by ‘binding’ your plug-in with the OpenLMIS SonarQube server, it uses the same set of rules and checks.

Ways to Use Sonar

There are three main use cases for Sonar that we are encouraging during the OpenLMIS v3 development:

1) SonarLint plug-in in IntelliJ. We encourage all developers to use it. We want to clean up code as we touch it (fix as we go).
2) During Reviews: Open Sonar to look at errors and issues in the code during a review. Also look at test coverage to consider whether the new code has enough tests. Bring up issues in the Fisheye review process.
3) Periodically Triage: The teams map pull up Sonar periodically to look at our most common issues and to look at broader trends in test coverage. We can use this to guide our discussions about what to prioritize as we work towards improved test coverage and quality.

False Positives

Sometimes SonarQube and SonarLint will show errors or issues that are not really a problem. A good time to discuss this is the code review process. If peers agree that something isn’t really a bug, we can leave it coded that way.

Although Sonar metrics are aligned with OpenLMIS coding standards, you may disagree with the filters and metrics that Sonar is using. If so, it’s worth bringing that up for team discussion. There may be rules we want to adjust or change. It is possible for us to adjust the rulesets and change our coding standards, but only after significant consideration. There is also good reason to stick with the industry-standard rules and best practices.

Feature and Advantage of using Sonarlint

Get the power to write better code

Bug detection

Benefit from thousands of rules ; which detect common mistakes, tricky bugs and known vulnerabilities.

Instant feedback

On-the-fly! Issues are detected and reported as you code, just like a spell-checker.

Know what to do

SonarLint precisely pinpoints where the problem is, and gives you recommendations on how to fix it.

Learn from your mistakes

Rich documentation lets you understand issues in detail and discover coding best practices.

Uncover old issues

See which issues were already existing, and become a hero for fixing them.

Best Alternative of Sonarlint

Top Alternatives to SonarLint
  • ReSharper. It is a popular developer productivity extension for Microsoft Visual Studio.
  • SonarQube. SonarQube provides an overview of the overall health of your source code and.
  • FindBugs. It detects possible bugs in Java programs.
  • PMD.
  • JSLint.
  • ESLint.
  • Pylint.
  • Checkstyle.

Best Resources, Tutorials and Guide for  Sonarlint

  1. devopsschool.com
  2. sonarlint.org
  3. sonarsource.com

Free Video Tutorials of  Sonarlint

Interview Questions and Answer for Sonarlint

  1. Difference between SonarQube and SonarLint?

SonarLint lives only in the IDE (IntelliJ, Eclipse and Visual Studio). Its purpose is to give instantaneous feedback as you type your code. For this, it concentrates on what code you are adding or updating.

SonarQube is a central server that processes full analyses (triggered by the various SonarQube Scanners). Its purpose is to give a 360° vision of the quality of your code base. For this, it analyzes all the source lines of your project on a regular basis.

Both SonarLint and SonarQube rely on the same static source code analyzers – most of them being written using SonarSource technology.

2. How to suppress warning for a specific method with Intellij SonarLint plugin?

The //NOSONAR tag is useful to deactivate all rules at a given line but is not suitable to deactivate all rules (or only a given rule) for all the lines of a method or a class. This is why support for @SuppressWarnings(“all”) has been added to SonarQube.

SINCE 2.8 of Java Plugin, you can also use @SuppressWarnings annotation with a list of rule keys:

@SuppressWarnings(“squid:S2078”) or

@SuppressWarnings({“squid:S2078”, “squid:S2076”}).

3. How to turn off SonarLint automatic triggering on IntelliJ IDEA?

For intellij:

Go to File -> Settings New window will open In new window Expand tools -> locate SonarLint and click on it. Under settings tab of SonarLint -> uncheck the box ‘Automatically trigger Analysis’.

Built-in string formatting vs string concatenation as logging parameter?

using SonarLint that shows me an issue in the following line.

LOGGER.debug(“Comparing objects: ” + object1 + ” and ” + object2);

Side-note: The method that contains this line might get called quite often.

The description for this issue is

“Preconditions” and logging arguments should not require evaluation (squid:S2629)

Passing message arguments that require further evaluation into a Guava com.google.common.base.Preconditions check can result in a performance penalty. That’s because whether or not they’re needed, each argument must be resolved before the method is actually called.

Similarly, passing concatenated strings into a logging method can also incur a needless performance hit because the concatenation will be performed every time the method is called, whether or not the log level is low enough to show the message.

Instead, you should structure your code to pass static or pre-computed values into Preconditions conditions check and logging calls.

Specifically, the built-in string formatting should be used instead of string concatenation, and if the message is the result of a method call, then Preconditions should be skipped altoghether, and the relevant exception should be conditionally thrown instead.

Noncompliant Code Example

logger.log(Level.DEBUG, "Something went wrong: " + message);  // Noncompliant; string concatenation performed even when log level too high to show DEBUG messages
LOG.error("Unable to open file " + csvPath, e);  // Noncompliant
Preconditions.checkState(a > 0, "Arg must be positive, but got " + a); // Noncompliant. String concatenation performed even when a > 0
Preconditions.checkState(condition, formatMessage());  //Noncompliant. formatMessage() invoked regardless of condition
Preconditions.checkState(condition, "message: %s", formatMessage()); // Noncompliant

Compliant Solution

logger.log(Level.SEVERE, "Something went wrong: %s", message);  // String formatting only applied if needed
logger.log(Level.SEVERE, () -> "Something went wrong: " + message); //since Java 8, we can use Supplier , which will be evaluated lazily
LOG.error("Unable to open file {}", csvPath, e);
if (LOG.isDebugEnabled() {   LOG.debug("Unable to open file " + csvPath, e);  // this is compliant, because it will not evaluate if log level is above debug. }
Preconditions.checkState(arg > 0, "Arg must be positive, but got %d", a);  // String formatting only applied if needed
if (!condition) {   throw new IllegalStateException(formatMessage()); // formatMessage() only invoked conditionally }
if (!condition) {   throw new IllegalStateException("message: " + formatMessage()); }

4. Cognitive Complexity and its effect on the code?

W.r.t to one of the java projects, we recently started using SonarLint. Output of the code analysis shows too many critical code smell alerts.

Critical code smell: Refactor this method to reduce its Cognitive Complexity.

5. Is Cognitive Complexity an industry standard?

Impacts of Cognitive Complexity on code apart from readability and maintainability.

Does Cognitive Complexity apply only to methods or any other parts of code?

Any specific criteria on which Cognitive Complexity depends on?

Best practices to improve Cognitive Complexity of a code.

6. How to use SonarLint in Eclipse?

If you want to analyze a complete project with the Sonar Lint plugin, you can trick the plugin by searching all Java files with a text editor and replacing “package” with ” package”. This will cause SVN or git changes. Open the “Sonar Lint Report” view and run the analysis on the “Current project”. Afterwards, revert all your SVN changes. Do not run the analysis again as the Sonar Lint Plugin only analyzes changed files.

7. How do you customize SonarLint rules in IntelliJ IDEA?

SonarLint 1.0 for Eclipse and IntelliJ do not allow to edit the quality profile (or set of rules) to be used for the analysis. Moreover, SonarLint 1.x works completely independently of a SonarQube server (having a SonarQube server is not a requirement), and therefore does not have the ability to reuse a quality profile defined there.

SonarLint 2.0 will have an optional mode that connects to a SonarQube server, and will offer this feature – but this isn’t available yet.

8. Sonarlint command line version dropped?

It would appear that Sonarsource has discontinued development on the command line instance of the sonarlint tool. The link to the page on the sonarlint website now returns a 404 and there is no mention of the product on the sonarlint website.

9. Disable sonarlint automatic analysis in Eclipse by default?

Window->Preferences->SonarLint->File Exclusions Then New GLOB Pattern: “**/*”

10. Unable to Finish connecting to SonarQube server?

SonarLint in Eclipse are storing credentials in Eclipse secure storage that itself is protected by a master password. So you must reset it or delete it to add a new SonarQube server connection. You can try this step :

In your Eclipse Go to Window > Preferences, filter and find Secure Storage.

In the Tab Contents find and highlight org.sonarlint.eclipse.core, click Delete > Apply > OK. After deletion process is finished, Eclipse will ask if you want to restart the IDE. It is strongly recommended that you restart the IDE and try again to adding SonarQube server in Eclipse.

11. Method has 8 parameters, which is greater than 7 authorized?

here are two things to consider here.

You can adjust this rule in Sonar and increase the number of authorized parameters. Say put it 10 instead of default (?) 7.

UPD: the advice below is based on the old question version. It might be not applicable to the new question context any more.

But generally you should reconsider your method interface. Having many arguments means that something can be wrong in your architecture and the Single responsibility principle might be broken.

Say in your particular example, I would expect, that you can have an aggregate class Order:

public class Order {
   private CountryCode countryCode;
   private String orderId;
   private User user;
   private String orderId;
   private String item;
   private List<Person> persons;
   private ShippingAddress address;
   private PaymentMethod payment;
   private Product product;
   // ...
}

Which is much logical to manage instead of dealing with many parameters. Then your issues will be solved automatically:

@GetMapping

public void updateSomething(Order order) { … }

12. What is the correct way to make a custom .NET Exception serializable?

namespace SerializableExceptions
{
    using System;
    using System.Runtime.Serialization;

    [Serializable]
    // Important: This attribute is NOT inherited from Exception, and MUST be specified 
    // otherwise serialization will fail with a SerializationException stating that
    // "Type X in Assembly Y is not marked as serializable."
    public class SerializableExceptionWithoutCustomProperties : Exception
    {
        public SerializableExceptionWithoutCustomProperties()
        {
        }

        public SerializableExceptionWithoutCustomProperties(string message) 
            : base(message)
        {
        }

        public SerializableExceptionWithoutCustomProperties(string message, Exception innerException) 
            : base(message, innerException)
        {
}

        // Without this constructor, deserialization will fail
        protected SerializableExceptionWithoutCustomProperties(SerializationInfo info, StreamingContext context) 
            : base(info, context)
        {
        }
    }
}

13. Is there a way to integrate sonarlint plugin in pom.xml?

SonarLint is a local plugin that can be embedded in your IDE. In the plugin setting you can put the “Automatically trigger analysis” in order to have feedback while writing.

In order to perform continuous integration you should use SonarQube, it is possible to integrate it with Jenkins or Codemagic and also with Maven. It is possible to add SonarQube to your pull requests as well.

Unable to trigger SonarLint Analysis on whole Project?

Open the SonarLint Tool Window, go to the Project files tab, and click in the “play” button. There is also an action to which you can assign a shortcut.

14. SonarLint Use the primitive boolean expression here?

As other already mentioned, Sonar wants you to make sure that you don’t have any null pointer exception, or at least that’s what i have seen too when i do a check before trying to validate against the variable:

if i have the next, Sonar complains

if (properties.getEnabled()) {
       // Your code
}
But if i add a quick validation against nulls, Sonar stops complaining about it

if (properties.getEnabled() != null && properties.getEnabled()) {
       // Your code
}
Now, as you mentioned you can use the Boolean class to use the next
Boolean.TRUE.equals(properties.getEnabled());
As
if (Boolean.TRUE.equals(properties.getEnabled())){
       // Your code
}

How to configure the rule set of SonarLint in Visual Studio Code?
Click on Edit in settings.json

Add to "sonarlint.rules": the rule you wand to disable as follow:

    "javascript:S1488": {
        "level": "off"
    }

15. How to install an older Eclipse plugin of SonarLint?

Instead of using Eclipse Marketplace, use menu in Help → Install New Software. Add sonarlint URL:

You will see all available version of sonarlint. If you already have it installed with unexpected version, you need to uninstall it first in Help → Installation Details.

Update your “SonarTS – Code Analyzer for TypeScript” (just push the button) Thats all. Don’t forget restart your server

16. How to exclude JS files from on-the-fly analysis in SonarLint for IntelliJ IDEA?

Settings

Other settings

Sonarlint General Settings

File exclusions

Press ‘+’

**/*.js

17. How to install sonarlint plugin in Platform: Eclipse Mars.1 (4.5.1)?

18. How to get SonarLint for Eclipse logs?

  • Open Eclipse Console view
  • Open the SonarLint Console image
  • Enable Verbose output and Analysis logs image
  • Reproduce the issue (e.g. reopen the offending file)

Sometimes errors are not in the SonarLint console, but could be directly in Eclipse error logs.

  • Open Eclipse Error Log view
  • Look for an error event related to SonarLint
  • Open event details to get the stacktrace

19. How SonarLint for Eclipse decides if a file is a test?

There is a regular expression you can configure in SonarLint settings to specify which files should be considered as tests.image

Recent Eclipse versions added the concept of test sources 55 (only for Java projects). When available, SonarLint will also rely on it (see the green icon for test folders).

image

In the end, if you want to know how a file was effectively classified by SonarLint, look at the SonarLint Console with Verbose output, and search for something like:

Starting analysis with configuration:

[
  baseDir: [...]
  workDir: [...]
  extraProperties: {sonar.java.target=1.8, [...]}
  inputFiles: [
    file:/home/julien/Prog/Projects/sonarlint-core/core/src/test/java/org/sonar/api/utils/log/SonarLintLoggerTest.java (UTF-8) [test]
  ]
]
and notice the [test] qualifier after the filename, to indicate SonarLint classified the file as test.

20. How to get SonarLint for IntelliJ logs?

Open the SonarLint tool window (View > Tool Windows > Sonarlint)

Enable Verbose output and Analysis logs SonarLintIntelliJ-Logs

SonarLintIntelliJ-Logs

1092×283 31.9 KB

Reproduce the issue (e.g. reopen the offending file)

 

 

 

Rajesh Kumar
Follow me
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x