The reason behind squid:S1258

java

(Ewa Śliwińska) #1

Hello,

I have a java bean class (private members, public no-argument constructor).
Part of fields can be optional, they are initialized with compiler-default values (nulls/falses for booelans), and can be set/changed later.
I would like to understand why

Non-abstract class es and enum s with non- static , private members should explicitly initialize those members, either in a constructor or with a default value.

I even can’t just put those values into field declaration, because that violates S3052 rule.

The only way to get rid of all violations is to provide a no-argument constructor which will initialize fields like the compiler does, and that looks just like clutter.


(Jens Bannmann) #3

I found that rule (S1258: Classes and enums with private members should have a constructor) to be strange as well. Maybe it’s just a matter of taste?

Note that with S3052: Fields should not be initialized to default values, SonarQube even has a rule which contradicts this rule (which in itself is not a bad thing, of course).


(Alexandre Gigleux) #4

Hello,

It should be mentioned that S1258 and S3052 are not activated by default to let you the choice to enforce one or the other policy and as @bannmann is saying, it’s a matter of taste.
Personally, I like to see what is the default value of a variable even if the same value is already set/initialized by the compiler. But it’s probably just because I’m switching too much between different languages during a week and I can’t remember what is the default values of all primitives depending on the context.

In your case, I would deactivate S1258 and keep only S3052.