Aggregrate @CommandHandler constructor delegates initialization to @EventHandler pattern

Hi,

I’m very new to Axon and I have been following the examples on the site and github and notice this pattern come up more than once:

public class ToDoItem ``extends AbstractAnnotatedAggregateRoot {

@AggregateIdentifier` private String id;`

public` `ToDoItem() {` }`

@CommandHandler` public ToDoItem(CreateToDoItemCommand command) { ```apply(``new ToDoItemCreatedEvent(command.getTodoId(), command.getDescription()));
```}`

@EventHandler` public void on(ToDoItemCreatedEvent event) { ```this``.id = event.getTodoId();
```} }`

I’m curious as to why the constructor cannot set its properties from the command and remove the need for the @EventHandler entirely. Is there a strategic or technical reason for this?

Thank you in advance,

Bob

Hi Bob,

There’s a technical reason. If the aggregate is event sourced, it will be recreated by applying the events sequentially. If the assignments aren’t in an event handler, the fields will not be set when the aggregate is rebuilt.

Ah, that makes a lot of sense since commands are not events and therefore will not be event sourced. Thanks for the crisp explanation!

I think this deserves mention in the documentation as this could really trip someone up if they did it the naive way.

Thanks again,

Bob

Hi Bob,

thanks for the feedback. I will add a little explanation to the getting started guide.
Basically, the rule is:

  • command handlers make decisions
  • event handlers change the state

Neither of the two does he other things. Once command handlers change state, that change will not be reflected when the aggregated is loaded back in. Axon’s GivenWhenThenTestFixture will detect this, and fail the test.

Cheers,

Allard

Awesome framework btw. Very impressed so far with the quality of the code and documentation. Keep up the great work!