Command Query Separation. How to handle error handling for mutating functions returning void

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/369370

  •  05-02-2021
  •  | 
  •  

Question

I am learning about SOLID principles in a Pluralsight course where Command Query Separation is being discussed. I am fine with the query functions returning something (and crucially being non-mutating).

The question I have is about commands. The idea here is that commands should return void. What if there is a problem executing the command? Some functions that might be mutating return a result code. This idiom is quite common in C programs. So how to address that.

Do you have to assume that these functions should always succeed? Or should it raise an exception if the function does not succeed?

How would you handle it if the language doesn't support exceptions, eg C?

Any comments?

Was it helpful?

Solution

Command/Query seperation is not really appropriate in a language which uses result codes. If you want to implement it in a laguage with result codes, you woud say that a "command" only returns a result code, while a "query" returns a struct or option with either a result code or an actual value.

OTHER TIPS

in Command Query Responsibility Segregation (CQRS for short) you often communicate between services using events. So your "new customer" command might lead to a "customer created" event. Your view might respond to that event by refreshing so the user will see the new customer in the list of customers.

The same thing goes for errors. a "new customer" command might lead to a "insufficient credit rating detected" event (an error for someone who doesn't meet some credit rating requirement) and anyone who needs to know that information could listen to that event.

For simple validations (like username being filled) a CQRS system just won't accept the command. Depending on your specific language you could actually return an error code here instead of void (throwing exception or http response codes are the other common ways to deal with this). The important thing to remember here is that an "ok" means that the command is actually being considered, not an ok in the terms that any and all services will be successful. Validation of your command should really just be limited to checks like are required fields filled and are numeric fields actually numeric.

Licensed under: CC-BY-SA with attribution
scroll top