CQRS: on Commands and Validation – part 2: the base handler
Last time we discussed how to use the Decorator pattern to validate our Commands. The approach works fine but while using it I started feeling something strange. It can be probably considered an elegant solution but there’s something missing, like a code smell.
What is the problem? Easy: how can you tell if you are really running the validation? What if you just “forget” to register the decorator? Nah, you need it.
Also, a better use for decorators should be all those cross cutting concerns like logging, tracing and so on.
Another very simple solution is to use a base class for the Command Handlers that takes an instance of IValidator as optional dependency and consumes it right before executing the command:
as you can see in this case the validator returns a “result” object that exposes a boolean status flag and a list of errors that may have occurred.
If the validation fails a specific exception is thrown, containing the list of errors.
If instead everything is ok, the protected method RunCommand() is executed, and that’s the only thing you have to implement in your Command Handlers 🙂