Qube: Community 9.9
The java rule S2390 produces a finding in the following case.
public class P
public static final P FOO = new C();
public class C extends P
I do understand and accept the argumentation in the rule description. But I don’t see, that it applies here. Well, yes, if C’s constructor accesses some of C’s members, the finding would be valid. But it doesn’t.
Now let’s modify P like this:
public class P
public static final Supplier<P> FOO = new SingleInstanceSupplier( C::new );
SingleInstanceSupplier is a class, that implements Supplier and creates a new instance, if get() is invoked the first time and for any succeeding invokation of get() returns that very same instance again.
This way we could workaround the pickyness of the rule. But unfortunately it doesn’t change behavior.
Shouldn’t this be valid?
Thanks for your message. What you’re saying is correct in both cases your code will work as expected. However, I feel like you’re missing the purpose of the too. The point is not just to show you that somewhere in the code you have a bug, but also to prevent you from writing the code that could lead to bugs in the future. For example, tomorrow you can modify your code and face some unpleasant
In the second example, it’s even trickier, we can’t guarantee that the supplier is called after the class is fully initialized. And while it might seem more safe, you can still face the same issue.
On the other hand, I can understand your pain, and if you’re actually implementing a singleton correctly, this issue sounds annoying. However, static analysis has its limitations, and the tool can’t know if you wrote something on purpose or if this is a mistake.
To me, it’s absolutely valid to ignore the issue in your case, cause you know what you’re doing, but I’d rather not change the rule implementation.
Thanks, Margarita, I do understand that.