Need some design pattern advise


(Joo) #1

Hi guys,

I guess I am not the only Lagom person who figured that the PersistentEntity class file can get quite huge when we start adding the command handlers with many different commands and the events.

I was trying to extract the handler blocks to the separate class files for better maintainability and readability. And I tried to come up with something like this.

trait CmdHandlerTrait[Cmd, ReplyType] extends PersistentEntity {

  override type Event = CustomerEvt

  def handle(cmd: Cmd, ctx: CommandContext[ReplyType], state: CustomerState): Persist

}

And then we use it like this:

trait SayHelloCmdHandler extends CmdHandlerTrait[SayHelloCmd, Done] {

  override def handle(cmd: SayHelloCmd, ctx: CommandContext[Done], state: CustomerState): Persist = {

     ctx.thenPersist(SayHelloEvt(name=cmd.name))(_=>ctx.reply(Done))
}

Then in the actual Entity, we mix-in this trait and for the command handler block for SayHelloCmd, we just call handle and pass the parameters.

    }.onCommand[SayHelloCmd, Done] {
      case (cmd: SayHelloCmd, ctx, state) => handle(cmd, ctx, state)

Do you think this is the scalable solution to the problem I am facing?

Any concerns about this kind of approach? Any better ideas?

Thanks,