When implementing a Command and a Handler in Kotli...
# announcements
c
When implementing a Command and a Handler in Kotlin, e.g. in CQS or CQRS architecture, what's your preferred approach and why? 1️⃣
class DoSomethingCommand : Command
in DoSomethingCommand.kt and
class DoSomethingCommandHandler : CommandHandler<DoSomethingCommand, R>
in DoSomethingCommandHandler.kt 2️⃣ same as above but in one file, e.g. DoSomething.kt 3️⃣ Command handler is an inner class of the command:
class DoSomethingCommand : Command { class DoSomethingCommandHandler : CommandHandler<DoSomethingCommand, R> }
If that matters, command dispatcher is used, so handlers are only addressed directly in tests, otherwise it's
commandInstance.execute()
where
fun Command.execute() = /* get command dispatcher from static context and dispatch the command */
t
IMHO the way you organize classes in files is purely a matter of taste, and all 3 should be valid, since inner (static) classes are compiled the same as top level classes. I'd say option 2 is better, because * you can define private constants or functions that are used for both command and receiver in the same file *
DoSomethingCommand.DoSomethingCommandHandler
is quite a long name, but if handler is not referenced everywhere in the code,
DoSomethintCommand.Handler
makes perfectly sense.
c
This may change before we go to production, but for now we went with option 1️⃣ for commands which can be called from another module and with option 2️⃣ for
internal
commands. Our main argument for this setup in our specific case is that we decided to have an
***.api
package which commands along with other API stuff belong to, while handlers are in other packages. This was decided because this'll make it easy to split the API into a separate lib if and when we need that.