CQS with out parameter

289 views Asked by At

In CQS (Command Query Separation) it is common to have commands with a "void" return value and Queries with a return type. (or so I have learned...)

Now I wonder if this COMMAND is valid then, because basically, we are doing the same thing as in a query, just with the "out" keyword instead of using the return type:

public class LogTrace{
    public Guid CorrelationId { get; }
    public DateTime Timestamp { get; }
}

public class Logger{
    public void Log(string message, out LogTrace trace){
        trace = new LogTrace(){//Fill properties};
        //Log the message (+ trace)
    }
}
2

There are 2 answers

0
Ant P On

CQS is not about "not having return types" but about not having queries change data or commands return state - it doesn't prescribe anything about how or when you should use language constructs because it's a language-agnostic concept.

Whether you return data from your command via an explicit return value or implicitly via the use of out parameters is really immaterial; you're still violating the same principle.

If anything, using out is worse: not only do you violate the principle but you also add unnecessary complexity to your code by trying to undermine yourself with a technicality. If you really need to return a value, you should use a proper return value for it.

I'd also question why you are trying to conform to architectural patterns that apparently do not fit with what you're trying to do (or further analyse what makes you think you need to return a value and address that underlying issue, depending on your perspective).

0
Daniel Lorenz On

Usually when you do CQS, you generally have ICommandHander<> and IQueryHandler<> so you can add decorators and get some really powerful cross-cutting concerns implemented. I went a step further and created a ICommandQueryHandler<>. There are gray areas, like Stacks/Queues where to get the data, you have to change it first. Thus, it is better to follow the standard as best you can, but just have something in place that you only use as a last resort when all the other options aren't going to work - and then use that each time to be consistent.