How would one apply command query separation (CQS), when result data is needed from a command?

后端 未结 10 1981
慢半拍i
慢半拍i 2021-01-30 06:25

In wikipedia\'s definition of command query separation, it is stated that

More formally, methods should return a value only if they are referentially t

10条回答
  •  失恋的感觉
    2021-01-30 07:04

    I see a lot of confusion above between CQS & CQRS (as Mark Rogers noticed at one answer as well).

    CQRS is an architectural approach in DDD where, in case of a query, you do not build up full blown object graphs from aggregate roots with all their entities and value types, but just lightweight view objects to show in a list.

    CQS is a good programming principle on code level in any part of your application. Not just the domain area. The principle exists way longer than DDD (and CQRS). It says not to mess up commands that change any state of the application with queries that just return data and can be invoked any time without changing any state. In my old days with Delphi, the lanquage showed a difference between functions and procedures. It was considered a bad practice to code 'functionprocedures' as we called them back than as well.

    To answer the question asked: One could think of a way to work around executing a command and getting back a result. For instance by providing a command object (command pattern) which has a void execute method and a readonly command result property.

    But what is the main reason to adhere to CQS? Keep code readable and reusable without the need to look at implementation details. Your code should be trustworthy not to cause unexpected side effects. So if the command wants to return a result, and the function name or return object clearly indicates that it is a command with a command result, I'll accept the exception to the CQS rule. No need to make things more complex. I agree with Martin Fowler (mentioned above) here.

    By the way: wouldn't strictly following this rule break the whole fluent api principle?

提交回复
热议问题