CQRS: business logic on the query side

前端 未结 3 924
栀梦
栀梦 2021-02-11 10:09

Following the concept of CQRS (Command Query Responsibility Segregation), I am directly referring the DAL in my MVC application and doing all reads via the ViewModels. However a

3条回答
  •  没有蜡笔的小新
    2021-02-11 10:39

    For your first scenario, I don't see why you need to do that calculation at the point of querying, neither do you need to use a calculated field. The domain could produce the calculated net wage when the appropriate employee transaction completes on the domain. The data produced gets consumed by the query side and gets stored in a view model field ready for querying.

    If the tax rate was changed, upon receiving notification (event) the query side would have to recalculate the net wage field for all the employee view models. This would happen as part of the save (asynchronously from the domain transaction) and not as part of a query request. Although the query side is doing this calculation, it is doing so based on numbers provided by the domain, so I don't see a problem with that.

    The main point: All calculations should be done via the domain or by query side event handlers prior to any queries.

    EDIT- Based on comment

    So for that particular 'what-if' analysis scenario, assuming that the data required is already in the query side - i.e. there is a 'EmployeeTimesheet' table that contains hours worked by employees, there's two options:

    1. Have a component on the query side that polls the employee data periodically and aggregates/sums the data into a 'Potential Wages' view model table, ready for management to see the current wage expenditure. The frequency of this polling would depend on how often the information was required. Perhaps they need this data to be valid within the hour, or perhaps daily is satisfactory.

    2. Again, have a 'PotentialWages' table, but that gets updated anytime an employee updates their time sheet or any time an employee's wage is changed. With this option the data would be kept close to real time.

    Either way, the aggregated data calculated is using figures produced by the domain and is done prior to the query so that the query is super simple and most importantly, super fast.

    EDIT 2 - Just to summarise

    In my mind, the domain should be responsible for doing calculations whereby the result of such calculations is required for decisions to be made. It's absolutely fine for the query/read side to be doing calculations for the sake of summing totals & aggregating data to give screens/reports the data they need, as long as this isn't part of the query itself.

提交回复
热议问题