The Sonar is an open source platform used by developers to manage source code quality and consistency.
It covers a wide area of code excellence checkpoints ranging from styling errors, potential bugs, and code defects to design inefficiencies, code duplication, lack of test coverage, and excess complexity.
Interview Questions And Answers:-
- 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)
21. How to get SonarLint for VSCode logs?
Enable SonarLint analyzer + verbose logs in VSCode settingsimage
image
735×253 13.7 KB
Open the Output view
Select the SonarLint output SonarLintVSCode-Console
Reproduce the issue (e.g. reopen the offending file)
22. How SonarLint for VSCode decides if a file is a test?
This is based on the file path + name. There is a glob pattern that can be changed in SonarLint settings. By default files are not considered as tests. For example, you can change the pattern to {**/test/**, **/*test*, **/*Test*}
23. How to ask for help?
Please describe your issue with a maximum of details. We will likely ask you for:
your IDE flavor/version/OS. Exemple: Eclipse 2018-12 on MacOSX
SonarLint version
Are you using connected mode?
If you are using connected mode, what is the SonarQube server version (or say if it is SonarCloud)
If you are using connected mode, what are the installed analyzers. You can easily get a list by opening https://<SQ server>/api/plugins/installed in a Web browser.
The full stacktrace of the error, and logs with Verbose output and Analysis logs enabled. See IDE specific section to find how to get SonarLint logs.
24. Java – SonarQube, issue on ‘Utility classes should not have public constructors’ (squid:S1118) in singleton?
Make your class final so that Instance creation can be avoided.
@SuppressWarnings("static-access")
public final class SuperClass {
private SuperClass() {
}
}
25. Exclude JS files from SonarLint?
Go to Window->Preferences, SonarLint->Scanner Properties and add the properties:
sonar.exclusions=**/*.js
sonar.test.exclusions=**/*.js
26. enable to configure SonarLint plugin on Idea IntelliJ?
Latest release of the SonarLint common library (used by most SonarLint flavors) unlock support of SonarTS. This is not yet officially supported in SonarLint for IntelliJ, but it will come.
SonarLint requires at least SonarTS 1.5, and it seems your have SonarTS 1.1.0 installed on your SonarQube server. So basically SonarLint is asking you to update it, and will ignore the plugin.
The classloader error should come from something else, but we need a stacktrace to better understand (look at SonarLint logs).
27. How to enable/disable any rule from SonarLint in Eclipse?
To Disable/Re-Enable Rules in SonarLint/Eclipse. -Window-Preferences-SonarLint-Rules Configuration. -Select Your Language(in my case Java). -Select the drop for changed rules or open the + symbol to show all rules.
28. Sonar – Make DATE_FORMAT as instance variable?
Static variable are mostly used for Constants.
Here you have declared static and assigning it instance of SimpleDateFormat.
Either make DATE_TIME_FORMAT non-static or assign a constant to this variable.
Better change it to instance variable and use a Sting to do that.
e.g public final String DATE_FORMAT = “yyyy-MM-dd’T’HH:mm:ss:SSS”;
29. SonarLint not working for coverage and duplications?
SonarLint doesn’t support those features, it goes out of its scope as SonarLint won’t necessarily scan the entire project. Sonar Lint only shows code issues.
Use SonarQube and one of its Scanners to have that information.
30. How does one mark issues as false positives in SonarLint?
Standalone Mode
Out of the box, in the stadanlone mode, SonarLint uses a set of default rules. You can find the list of rules in the SonarLint webpage.
31. Intellij SonarLint 2.3 – ignore rule?
32. Sonarlint complains about license header in my source file?
just removed ; from Licensed under the Apache License, Version 2.0 (the “License”); and sonar lint warning gone.
33. How to disable SonarLint for test projects?
In Visual Studio, open the project and then dig into the Reference section. There choose to edit the active rule set:
Open Active Ruleset
In the screen that opens select/deselect the rules you want for the specific project. Then hit save. This will most likely create a new .ruleset file in your project and instruct Roslyn to use that instead of the standard set.
The result is that the project file is updated with the <CodeAnalysisRuleSet> tag like this:
<CodeAnalysisRuleSet>UnitTests.Core.ruleset</CodeAnalysisRuleSet>
You can also use the add new file wizard and pick the “Code Analysis Rule set” option:
enter image description here
Then from the Analyze menu select “Configure Code Analysis for Solution”, your newly added rule set can be selected from there and assigned to the project you want.
34. How to disable todo warnings in sonarlint plugin for IntelliJ?
Regarding the highlighting issue: You need to go to Settings > Editor > SonarLint, then click on “Info issue”, disable “Inherit values from” and set your preferred error stripe mark.
35. Does SonarLint provide any advantage over SonarAnalyzer.CSharp?
SonarLint for Visual Studio adds the following functionality to SonarAnalyzer.CSharp (I could be missing minor features):
JavaScript, TypeScript and C/C++ support.
Background source code analysis – to be fair, adding the nuget will make your builds slower. When you use SonarLint instead of the nuget your local builds will not be slower.
Ability to “connect” a solution to a SonarQube server, which allows you to automatically sync rulesets and settings.
QualityGate pass/fail notifications within Visual Studio.
SonarLint is somewhat easier to update than the nuget and you could benefit from the latest fixes and improvements without much effort.
In general, the biggest benefit is that you will be able to analyze supported non-.NET languages in your solution and/or probably the slight performance improvement of the background analysis.
36. SonarLint ignores quality profile from server?
the issue on SonarLint for Visual Studio and SonarQube Server 5.4. SonarLint uses generic default rules, instead of custom Quality Profile defined on server.
SonarLint Eclipse : Does it also analyze source code in “src/test”?
In SonarLint for Eclipse, you can configure which files are considered to be test sources.
Go to:
Preferences -> SonarLint
And change the “Test file regular expressions”.
Sonarlint compaining about unused variables that really are used?
I have a piece of code that looks like this:
public void test() {
Stream.of(aSet.entrySet(), anotherSet.entrySet())
.flatMap(Collection::stream)
.forEach((es) -> {
try {
//Complains on unused variable message.
Value value = es.getValue();
...use value.
} catch (IllegalArgumentException e) {
String key = es.getKey();
//Complains on unused variable message.
String message = " (#" + key + ")";
throw new IllegalArgumentException(message, e);
}
});
}
37. Which statement is correct?
Sonar will run CheckStyle, FindBugs and PMD by default for Java projects (Ans)
Sonar will run Checkmate by default for Java projects
Sonar will run FindIssue by default for Java projects
Sonar will run PMDtest by default for Java projects
38. Which is not an axis of code quality in SonarQube?
- Architecture and Design
- Complexity
- Potential bugs
- Code Coverage (Ans)
39. What is the prerequisite for SonarQube Installation?
- Java (Ans)
- DOTNET
- JavaScript
- Php
40. Which is not part of Code Technical Review in SoanrQube?
- Confirm
- Change Severity
- Resolve
- Submited (Ans)
41. What is not a search criteria for the rules in SonarQube?
- Language
- Type
- Tag
- Develop (Ans)
42. Which is the not found in sonar-project.properties?
- sonar.projectVersion
- sonar.sources
- sonar.code (Ans)
- sonar.language
43. Which property should be decalred for SonarQube Project base dir?
- sonar.projectBaseDir (Ans)
- sonar.working.directory
- sonar.basedir
- sonar.projectdir
44. Which property should be decalred to tell SonarQube which SCM plugin should be used to grab SCM data on the project
- sonar.scm.provider (Ans)
- sonar.scm
- sonar.git
- sonar.version
45. Which property should be decalred to tell SonarQube log level?
- INFO
- DEBUG
- TRACE
- ERROR (Ans)
46. Which is not supported Log Level in SonarQube?
- sonar.log.level
- sonar.verbose (Ans)
- sonar.log
- sonar.loglevel
47. Is it right definition of Code Smell? A maintainability-related issue in the code. Leaving it as-is means that at best maintainers will have a harder time than they should making changes to the code. At worst, they’ll be so confused by the state of the code that they’ll introduce additional errors as they make changes.
YES (Ans)
NO
48. Is it right definition of Coding Rule? A good coding practice. Not complying to coding rules leads to quality flaws and creation of issues in SonarQube. Coding rules can check quality on files, unit tests or packages.
YES (Ans)
NO
49. Is it right definition of Analyzer? A client application that analyzes the source code to compute snapshots.
YES (Ans)
NO
50. Which is not severities in Sonarqube?
- Options
- Blocker
- Major
- Critical
- Issues (Ans)
Here is the video link that will help:-
- Installing Jupyter: Get up and running on your computer - November 2, 2024
- An Introduction of SymOps by SymOps.com - October 30, 2024
- Introduction to System Operations (SymOps) - October 30, 2024