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

后端 未结 10 2001
慢半拍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 06:48

    Take some more time to think about WHY you want Command Query Separation.

    "It lets you use queries at will without any worry of changing system state."

    So it is OKAY to return a value from a command to let the caller know it succeeded

    because it would be wasteful to create a separate query for the sole purpose of

    finding out if a previous command worked properly. Something like this is okay in

    my books:

    boolean purchaseSucceeded = _storeService.PurchaseItem(buyer, item);
    

    A disadvantage of your example is that it is not obvious what is returned by your

    method.

    string result = _storeService.PurchaseItem(buyer, item);
    

    It is not clear what 'result' is exactly.

    Using CQS (Command Query Seperation) allows you to make things more obvious

    similar to below:

    if(_storeService.PurchaseItem(buyer, item)){
    
        String receipt = _storeService.getLastPurchaseReciept(buyer);
    }
    

    Yes, this is more code, but it is more clear what is happening.

提交回复
热议问题