If you are forced to use an Anemic domain model, where do you put your business logic and calculated fields?

后端 未结 8 1571
南旧
南旧 2020-12-22 19:49

Our current O/RM tool does not really allow for rich domain models, so we are forced to utilize anemic (DTO) entities everywhere. This has worked fine, but I continue to st

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-22 20:21

    If you want to add a bit of behavior to your entities, but can't modify your entities, give extension methods a try. I'd only do this for simple scenarios like in your example though. Anything more complex or that coordinates between several entities and/or services, layers, or whatever should be in a domain service as suggested already.

    For example (from your examples):

    public static class LineItemEntityExtensions
    {
      public static decimal CalculateTotal(this LineItemEntity li)
      {
        return li.Quantity * li.Price;
      }
    }
    
    public static class OrderEntityExtensions
    {
      public static decimal CalculateOrderTotal(this OrderEntity order)
      {
        decimal orderTotal = 0;
        foreach (LineItemEntity li in order.LineItems)
          orderTotal += li.CalculateTotal();
        return orderTotal;
      }
    }
    
    public class SomewhereElse
    {
      public void DoSomething(OrderEntity order)
      {
        decimal total = order.CalculateOrderTotal();
        ...
      }
    }
    

    If there are very few of these additions that you want, you can just put them all in a "DomainExtensions" class, but I'd otherwise suggest treating them with regular respect and keep all of an entity's extensions in one class in its own file.

    FYI: The only time I've done this is when I had a L2S solution and didn't want to mess with the partials. I also didn't have many extensions because the solution was small. I like the idea of going with a full blown domain services layer better.

提交回复
热议问题