Support Java custom meta-annotations to selectively ignore some rules

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.

Hi,

I can’t address whether or not to change how issue suppression works with Java annotations. I can, however, offer you an alternative, which is multi-criteria issue suppression. Assuming your view file paths all match some regex, you could set it up to ignore java:S1104 on **/views/*.java (or whatever).

 
HTH,
Ann

Hi,

Thanks for your suggestion. We can indeed apply your suggestion (and will do)!

That being said, I prefer a solution where code remains the single “source of truth” telling if a rule needs to be applied or not (i.e. no specific configuration nor naming convention is required).

What’s your opinion on this?

Gérard

Hi,

No real opinion. I’ve seen strong (and decently reasoned) arguments on both sides.

 
Ann

OK, thanks. Is there any chance to see this as a feature of SonarJava in the future (i.e. would it make sense that I work on a pull request for this) or should I just forget about it? :slight_smile:

Hi,

I can’t answer that directly. The guys that work on the analyzer will be along at some point and may comment. In the meantime, this sits in the ‘Suggest new features’ category and is open to gather votes and support.

 
Ann

All right, thank you!