Hello
I read here, that explicitly writing a totally empty no-arg constructor in a class, which implements Serializable, is not only all right, as absolutely necessary in some cases.
If this is true, how does this play with the rule Methods should not be empty?
The rule advises: “This does not raise an issue in the following cases: Non-public default (no-argument) constructors; Public default (no-argument) constructors when there are other constructors in the class”.
Now, we’re getting hundreds of violations to this rule, in our 10.5.1 SonarQube instance, with classes, which implement Serializable, which contain an explicit public empty no-arg constructor, and do not contain any other constructors.
How should we see this: an issue, a false positive?
If the latter, won’t the rule need to be improved?
Thanks in advance!
Hello Duarte!
The solution here would be to insert a comment into the empty constructors explaining why they are required. In that case, S1186 won’t report, as a block containing a comment is regarded “not empty”. You could do something like this:
class Foo implements Serializable {
public Foo() {
// required for serialization
}
}
This is a good practice because it shows that the method was intentionally left empty, not by accident, and also gives a reason why we need this exception from the rule here.
Cheers,
Marco