Why are userId and passwordHash set in onUserCreated and not directly in the constructor in User Aggregate (axonTrader)

Hi Guys,

I’m trying to understand why the userId and passwordHash are not set directly in the constructor of the User aggregate. I understand why the constructor applies a UserCreatedEvent but i’m not really sure why one would not directly set the userId and passwordHash in the constructor.

Kind regards,
Robby

public class User extends AbstractAnnotatedAggregateRoot {
    private static final long serialVersionUID = 3291411359839192350L;
    @AggregateIdentifier
    private UserId userId;
    private String passwordHash;

    protected User() {
    }

    public User(UserId userId, String username, String name, String password) {
        apply(new UserCreatedEvent(userId, name, username, hashOf(password.toCharArray())));
    }

    public boolean authenticate(char[] password) {
        boolean success = this.passwordHash.equals(hashOf(password));
        if (success) {
            apply(new UserAuthenticatedEvent(userId));
        }
        return success;
    }

    @EventHandler
    public void onUserCreated(UserCreatedEvent event) {
        this.userId = event.getUserIdentifier();
        this.passwordHash = event.getPassword();
    }

    private String hashOf(char[] password) {
        return DigestUtils.sha1(String.valueOf(password));
    }

    @Override
    public UserId getIdentifier() {
        return userId;
    }
}

Hi Robby,

if you would set the values directly in the constructor, they won’t be set when the aggregate is reconstructed from its event stream.
I notice you have a getter on your aggregate. That’s a smell of a violation of CQRS principles… The Aggregate is for “C”. For queries, you should use another model.

Cheers,

Allard

Hi Allard,

I actually copy pasted this code from the AxonTrader demo app… :slight_smile: Jettro Coenradie was the author of this Aggregate… But thanks for the insight !!