In our code base, the objects exchanged via our REST API are defined as classes (views) with all fields public, no constructor (i.e. there is only the default constructor) and no methods (and we use Jackson to map them from/to JSON, but that’s a detail). We consider the lack of encapsulation as acceptable as we consider those classes as just a way of documenting the data exchanged via our API.
Sonar Java obviously rises issues on each field because of rule java:S1104.
As we want to ignore the issues, we annotate our views with @SuppressWarnings("java:S1104")
and add a comment supporting this (e.g. “this is a view”).
In order to have a more explicit code base, we introduced a @View
annotation that combines the warning suppression and the explanation. We defined the annotation as follows:
@Documented
@Inherited
@Retention(RetentionPolicy.SOURCE)
@Target(TYPE)
@SuppressWarnings("java:S1104")
public @interface View {
}
so that our code, which was looking like this:
@SuppressWarnings("java:S1104") // it's a view
public class MyView {
public int aField;
}
looks like that:
@View
public class MyView {
public int aField;
}
Unfortunately, this is not recognized by the Java code analyzer.
It would be great if the general approach (i.e. custom meta-annotations disabling selectively rules) was supported, both by the Java code analyzer and SonarLint (I don’t know to which extent upgrading one benefits to the other).
Note that I would be happy to contribute a pull request if the feature makes any sense to the community.