S1144 says CDI observer method is unused

SonarJava’s S1144 claims that CDI observer methods are unused and suggests removing them:

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Initialized;
import javax.enterprise.event.Observes;

import com.example.event.LoggedInEvent;
import com.example.model.Foo;

class MyClass
{
    private void init(@Observes @Initialized(ApplicationScoped.class) Object init) { }

    private void afterLogin(@Observes LoggedInEvent event) { }

    private void afterFooUpdate(@Observes @Updated Foo foo) { }
}

The rule already excludes all methods that have annotations, but with these methods, only the event parameter is annotated. (Note that there may be additional parameters that are injection points and may or may not be annotated.)

The fix should be to ignore any methods that have a parameter annotated with javax.enterprise.event.Observes.

A workaround would be to declare the methods public, but I consider this bad practice as doing so could lead to developers calling these methods from other classes although the methods are not intended for that.

This happens with SonarQube 8.9.9, but the cause is SonarJava’s UnusedPrivateMethodCheck class which according to the 7.14.0.30229 sources still does this.

Hello @bannmann,

Thanks for your message.

Of course, you shouldn’t make methods public just to please a Static analysis tool. Anyway, it’s just a tool and it can make mistakes.

This case is indeed a false positive. I’ve created a ticket to fix it. So you can track progress no it. Meanwhile, you can mark these issues as false positives in SQ.

Regards,
Margarita

2 Likes

Hi @Margarita_Nedzelska,

thanks for the ticket! I have two additions:

  1. In the ticket, you wrote:

    the simplest solution would be to ignore all methods with annotated parameters

    Actually, I would strongly advise against that: in my opinion, this would offer no benefit, but increase the chance of false negatives. Parameters are often annotated with nullability annotations or Lombok’s code-generating @NonNull annotation, and their presence does not at all imply that the methods are “used”.

    Therefore, the addition to the rule should only be about parameters annotated with javax.enterprise.event.Observes. There may be other such annotations, but personally, I don’t know any - for example, the Spring Framework does not use parameter annotations for its observer/event pattern.

  2. In my example, @Updated is supposed to be a custom annotation. To avoid confusion, please add import com.example.annotations.Updated; to the code block in the ticket.

Best regards,
Jens

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.