design-patternsdomain-driven-designcqrscommand-pattern

What is the difference between Command + CommandHandler and Service?


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:

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?


Solution

  • 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.