I have been reading about using Command objects to represent use cases that our domain exposes, and Command Handler objects to process those commands.
For example:
RegisterUserCommand
RegisterUserCommandHandler
But it looks exactly the same as having a RegisterUserService
, where the command object would represent the parameters to the registerUser()
method.
And of course, if the method had too many parameters, I would end up creating an object to wrap them and that object would be the same as the RegisterUserCommand
.
So why have a different pattern to represent the same thing? Services are widespread, not Commands (from my experience); what is the difference here that I am missing? In short, why would I use one rather than the other?
A Command Handler is essentially a way to separate your commands into different files, instead of having a bunch of if/else conditions inside your code (or a switch/case if you're being fancy). In this case, the code shows you how to separate each command into its own file.
Command Handler is a library for Flask framework which provides: API method for posting new commands, tools for easy command handlers management.
Differences between Events and Commands Events represent a past, something that already happened and can't be undone. Commands, on the other hand, represent a wish, an action in the future which can be rejected. An event has typically multiple consumers, but a command is addressed to only one.
Command Classes. A command is an object whose role is to store all the information required for executing an action, including the method to call, the method arguments, and the object (known as the receiver) that implements the method.
Having Commands gives you the benefits of the good old Command pattern:
If your services were large, each with many complex methods (and if the methods weren't complex you probably shouldn't be using DDD or CQRS), then moving each method into a Command Handler might improve your application by making it more composable, easier to test, etc. No doubt it is common for people who refactor straight from big services to Commands/Command Handlers to regard this as a benefit of the latter pattern. But you could get the same benefit by decomposing large services into smaller ones (as suggested by the very specific service in your example), so strictly speaking that isn't a difference between services and Commands/Command Handlers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With