DDD中的标识符与参考

时间:2014-09-15 19:10:21

标签: domain-driven-design aggregate ddd-repositories ddd-service

我有两个案例,我可以使用是否为实体的id或将其作为参考传递。

1)域名服务。例如:

class ProductService {
     public void changePrice(Product product, long newPrice) {
          // significant calculations involving several Entities here...
     }
     // versus
     public void changePrice(long productId, long newPrice) {
          Product product = productRepository.get(productId);
          // significant calculations involving several Entities here...
     }
}

2)实体。例如:

class Order {
    public void addItem(Product product, long quantity) {
        // do stuff
    }
    // versus
    public void addItem(long productId, long quantity) {
        Product product = Registry.productRepository().get(productId);
        // do stuff
    }
    // or even maybe this ugly version?
    public void addItem(ProductRepository productRepository, long productId, long quantity) {
        Product product = productRepository.get(productId);
        // do stuff
    }
}

哪种方法更好,为什么?

1 个答案:

答案 0 :(得分:2)

我喜欢Onion Architecture视图,了解如何从概念上考虑如何保护您的域免受外部影响。

IMO,将存储库保留在域外是最好的。让域外的图层解析域实体,然后在域中使用它们

所以,我显然希望看到直接使用Product的示例(参考)。存储库的实现不在域中。域不应该与ID,配置或持久性混杂在一起。相反,它应该直接关注域问题,并尽可能清晰。

相关问题