Sonar rule for interfaces only RSPEC-1213 - java

I want to modify / make the rule target only public interfaces (not public classes etc). Is this possible ? Im using this rule in Java code but its too strict for my project and I would love to know if there is a way to change it a little bit.
Link for rule: https://rules.sonarsource.com/java/RSPEC-1213

For an existing ruleset on SonarQube, talk to your sonar administrator to change the rules that are enforced on the code and remove that particular one from global enforcement.
There have been a few times I've gone to the admins of the tool for the install that I use and said "this rule isn't one that I care about or will enforce and only makes it confusing" and had them remove that rule from the globally run ruleset.
Is it possible to write your own rule?
Yes, it is possible. From SonarQube's docs: Adding coding rules you have some options. Either you can write a plugin for SonarQube and add that to your instance (docs), or you can write an external application that analyzes the code which SonarQube consumes.
If you don't have your own instance of sonarqube or aren't up to writing the associated plugin or external tooling... you might want to instead lookout PMD (site).
For PMD, writing a custom rule can be much simpler (docs). One of the ways that PMD works is by 'compiling' the Java code into an XML representation of the abstract syntax tree for Java and then running xpath queries against that XML (tutorial).
The xpath rule can then be included in a project's configuration.
What about turning it off for the code that I'm working on?
If a specific rule is one that you don't want to invoke, you could suppress it with #SuppressWarnings("java:S106") (that particular spares warnings is for System.out.println use, but the same structure can be used for other warnings) or by adding // NOSONAR too strict on the line. There are spots where I have such comments where following the rule for a particular set of code is problematic and suppress it for that line, method, or class - with the comment about why that is done.
That particular rule... I'm gonna agree with the Java (and now Oracle) guidelines and follow it. The reason is that if anyone else works on the code, they'll expect it to follow that convention. Having a consistent understanding of what things should be where in code so that another developer doesn't need to go dig through an entire file to find the constructor when it is expected to be at the top (under the field definition) is a good thing. What's more, it limits the future cases where a developer goes through to make things consistent with conventions and results in a lot of style: updating code to follow style guide commits later.

Related

How to enforce this pattern via gradle plugins?

We are trying to keep our code 'consistent' over time on our projects and follow this pattern
https://blog.twitter.com/engineering/en_us/topics/insights/2019/onepattern.html
For any classes annotated with #Entity or #Data, we consider these data objects and would like to enforce that
The new keyword cannot be used on any objects NOT annotated with #Data (ie. all business logic is created by guice) - This is the hard one here!
Only get/set/is member methods are in the data objects(perhaps along with equals) - This could be done by scanning and reflection
All objects with no #Data are annotated with #Singleton(we program in stateless) OR with #ExceptionNotSingleton for exceptions (our exceptions are very rare as we build stateless systems - Could again be done with scanning and reflection
NO static methods allowed on business objects even utilities -> scan and reflection
The 4th point is for a specific project webpieces where since we use that platform, we can fix bugs in any code by swapping out the class. swapping static methods doesn't work very well.
What tool can do something like this such that I can feed it a simple processor? A gradle plugin would be nice where I can feed it some small snippets of code, but I am not sure that exists.
I could add a unit test to every project as well I guess and then just need a class scanner to inspect the classes.
I am looking for a plugin perhaps with a link to some examples I could try out.
What you're talking about is similar to static code analysis.
The basic (and simplified) idea is to parse the source code into a tree and then analyze that tree for the specific patterns you're looking for.
In you case, for example, whenever you see a constructor invocation in the tree, you check whether the target class is annotated with #Data or not. Or, whenever you're analyzing a class, you visit all its method leaves and look for statics. If you spot violations – you log them and probably break the build.
The trick here is to define your rules in the term of formal patterns in AST tree.
There are a plenty of code analyzers for Java, but IMHO the most popular one is Checkstyle. All of them probably work nice with Gradle (Checkstyle and PMD do), so it's not really a question about build tool, but about extending the analyzer.
Usually, static code analyzers allows users to extend them with custom checks / rules / plugins / etc. So does Checkstyle: read more about writing new checks. This article describes the AST and navigation in details. Checkstyle also provides a GUI tool to analyze Java classes to help find the patterns and write checks. Go ahead an load some of you clases there and look if you can track your issues via AST tree.
When you're comfortable with AST, its navigation, visitors and so on – go and write your own checks and integrate them in you build.
This idea is applicable for other static code analyzers as well, like PMD or SpotBugs (although SpotBugs's docs are poor).

Why java method name should not contain underscore?

I am using PMD for checking java coding violation.
I am writing automation test cases, and given method name like this:
public void testCaseMethod_4_2_16(){
//some implementation
}
where 4_2_16 is test case number 4.2.16
and when I check for PMD violation it is showing method name should not contain underscore, and this violation is shown as blocker according to PMD rules.
So here are my question:
Why method name should not contain underscore is define as a blocker or PMD error?
What kind of PMD violation we should avoid and
What kind of violation we should try to fixed?
As for my understanding at least we should avoid first two level of violation shown by PMD.
Any help on the PMD rule will be appreciated. thanks
It is a standard that has been set so that people can easily read each other's code, therefore making code more maintainable.
The quote below is from Oracle's website on Java code conventions:
80% of the lifetime cost of a piece of software goes to maintenance.
Hardly any software is maintained for its whole life by the original author.
Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly.
Java prefers camelCase notation. Java code conventions say that you should try to avoid underscores in method or variable name whenever it is possible.
In your case PMD's default prioritization fails. This rule should be on a "nice-to-have" level, but definitely not a blocker issue.
I would recommend you to use SonarQube, which did a re-prioritization of PMD's rules, which works better is most cases. The rule you found is just on Major level (below levels Blocker and Critical).
If you are still not satisfied with the results, you can use the SourceMeter plugin for SonarQube, which has a different (possible better) prioritization of PMD rules as well.
Although there are lots of opinions out there, I like to separate quality-assurance for production and the one for test code.
If that is not possible for whatever reason, I'd rather deactivate (most of) the warnings for test-code. I think it is not worth the time making the test-code pretty (and underscores in method names is just styling to me), while there are serious warnings for the production code left open.
In java underscore is allowed while naming identifiers. I don't know why PMD is showing violation but you can just deactivate the warnings and go on. UNDERSCORE is allowed in java while naming identifiers.
I think it may help you...

Is there a Java tool to reduce the visibility of methods

I have a legacy code base that I want to refactor to reduce the visibility of methods to the minimum possible (private, protected, default) such that the code still works. Many of the methods in the codebase are unnecessarily public, and I'd like to change that to reduce the interface burden and simplify documentation as the code evolves in the future. Is there a tool that will analyze the codebase and generate a list of suggested methods whose visibility can be reduced? I can specify all the entry points into the code (just the main methods), and the codebase doesn't use reflection.
An Eclipse plugin will be even better.
Take a look at UCDetector (Unnecessary Code Detector - pronounced "You See Detector")
http://www.ucdetector.org/
It is an eclipse plugin and it helps to reduce visibility. I have used it for long time and it works very well.
Although there are tools that you can use to report the occurrence of methods which visibility can be reduced, I am not aware of something that allows you to transform the code to solve those issues.
However, you may find interesting taking a look to JTransformer and Ekeko.
Both allows you to query and accomplish custom code transformations based on logic programming techniques. JTransformer may be a bit more mature, but Ekeko also looks quite interesting. To the best of my knowledge they both are open source and include an Eclipse plugin.

Plugging in to Java compilers

I have a post-compilation step that manipulates the Java bytecode of generated classes. I'd like to make life as painless as possible for library consumers, so I'm looking at ways I can make this process automatic and (if possible) compiler agnostic.
The Annotation Processing API provides many of the desired features (automatic service discovery; supported by Eclipse). Unfortunately, this is aimed at code generators and doesn't support manipulation of existing artefacts:
The initial inputs to the tool are
considered to be created by the zeroth
round; therefore, attempting to create
a source or class file corresponding
to one of those inputs will result in
a FilerException.
The Decorator pattern recommended by the API is not an option.
I can see how to perform the step with a runtime agent/instrumentation, but this is a worse option than a manual build step as it would require anyone even peripherally touched by the API to configure their JVMs in a non-obvious manner.
Is there a way to plug into or wrap the compiler tool as invoked by javac? Has anyone successfully subverted the annotation processors to manipulate bytecode, no matter what the doc says?
The Groovy compiler is the only bytecode compiler which allows to hook into the compilation process (example: Generate bytecode to support the Singleton pattern)
The Annotation Processing API is not meant to change the code. As you have already found out, all you can do is install a classloader, examine the bytecode at runtime and manipulate it. It's braindead but it works. This follows the general "we're afraid that a developer could try something stupid" theme which you will find throughout Java. There is no way to extend javac. The relevant classes are either private, final or will change with the next version of Java.
Another option is to write annotated Java, for example you write a class "ExampleTpl.java". Then, you use a precompiler which expands the annotations in that file to get "Example.java". In the rest of the code, you use Example and ignore ExampleTpl.
For Eclipse, there is a bug report to automate this step. I'm not aware of any other work in this area.
It can be done.
Take a look at my blog post Roman Numerals, in our Java where an annotation processor is used to rewrite code. Limitation being that it works with Sun's javac only.

Cross-class-capable extendable static analysis tool for java?

I'm trying to write rules for detecting some errors in annotated multi-threaded java programs. As a toy example, I'd like to detect if any method annotated with #ThreadSafe calls a method without such an annotation, without synchronization. I'm looking for a tool that would allow me to write such a test.
I've looked at source analyzers, like CheckStyle and PMD, and they don't really have cross-class analysis capabilities. Bytecode analysers, like FindBugs and JLint seem rather difficult to extend.
I'd settle for a solution to something even simpler, but posing the same difficulty: writing a custom rule that checks whether each overriden method is annotated with #Override.
Have you tried FindBugs? It actually supports a set of annotations for thread safety (the same as those used in Java Concurrency in Practice). Also, you can write your own custom rules. I'm not sure whether you can do cross-class analysis, but I believe so.
Peter Ventjeer has a concurrency checking tool (that uses ASM) to detect stuff like this. I'm not sure if he's released it publicly but he might able to help you.
And I believe Coverity's static/dynamic analysis tools for thread safety do checking like this.
You can do cross-class analysis in PMD (though I've never used it for this specific purpose). I think it's possible using this visitor pattern that they document, though I'll leave the specifics to you.
A simple tool to checkup on annotations is apt (http://java.sun.com/j2se/1.5.0/docs/guide/apt/ also part of Java 6 api in javax.annotation.processing) however this only has type information (ie I couldn't find a quick way to get at the inheritance hierarchy using the javax.lang.model api, however if you can load the class you can get that information using reflection).
Try javap + regexes (eg. Perl)

Categories