Search code examples
javaeventsjakarta-eecdi

why is the CDI Event generic?


let's assume I have an AccountService that notifies when an account is created or deleted. How would the 2 following implementation be of any difference?

@Stateless
public class AccountService {

    @Inject
    protected Event<AccountCreated> accountCreated;

    @Inject
    protected Event<AccountDeleted> accountDeleted;


    public UserAccount createAccount(...) {
        ...(do stuff)
        accountCreated.fire(new AccountCreated(...));
    }

    public UserAccount deleteAccount(...) {
        ...(do stuff)
        accountDeleted.fire(new AccountDeleted(...));
    }
}

and the simpler version:

@Stateless
public class AccountService {

    @Inject
    protected Event<Object> events;


    public UserAccount createAccount(...) {
        ...(do stuff)
        events.fire(new AccountCreated(...));
    }

    public UserAccount deleteAccount(...) {
        ...(do stuff)
        events.fire(new AccountDeleted(...));
    }

}

I'm currently using the 2nd approach, but am wondering if I'm not doing it right.


Solution

  • What your are asking about is mostly good practice or in some cases personal preference (or the voice of majority?).

    Both approaches would work, however the first one would be considered cleaner as it clearly shows what are you working with from the first look at it.

    Furthermore, your second example is going to get messier if you start using qualifiers.

    And if you were to ask similar question about Instance<Object>, then there would be additional reasons (to use first approach) - resolution checks during deployment, optimizations not working.