Using invoke/execute in command handlers

Just a quick question about best practices when using external command handler (not handling commands on the aggregate )

Both Axon Trader and Axon Bank both heavily use the “execute()” method (which belongs to the Aggreagate class) in the command handlers.

However, the java doc for “org.axonframework.commandhandling.model.Aggregate#execute” says:

/**
 * Execute a method on the underlying aggregate or one of its instances.
 * <p>
 * Note that the use of this method is not recommended as the wrapped aggregate instance is not meant to be
 * exposed. Relying on this method is commonly a sign of design smell.
 *
 * @param invocation The function that performs the invocation
 */
void execute(Consumer<T> invocation);

So my questions are:

  1. Is it ok to use “execute” everywhere as shown in the example projects, or should it be only used in certain scenarios and what are those scenarios, if any?
  2. If the JavaDoc is accurate then what is the preferred way of calling methods on your aggregate (assuming you still want to use a separate object for command handling)?
    Thanks for your time

Rich

Hi Rich,

thanks for pointing this out. I think the javadoc is slightly harsh on this one. It’s bad practice to use the invoke method (which gives you a return value) if that is being used to get information out of the aggregate (i.e. a query). However, if you have an external Command Handler, this method is the best way to interact with the aggregate.

Still, the preferred way to interact with an Aggregate is through command objects and @CommandHandler annotations on the aggregate itself. If that is not possible, then the execute() method is a good alternative.

Cheers,

Allard

Cool, thanks for the reply :slight_smile: