Which of these examples represent the correct use of DDD?

I have been working with DDD for several months, and I have come across some things that I don’t know about.

Take a simplified example of adding a Product object to an Order object. From our controller, we would pass int through the interface that represents the Product in the database. Which of the following two examples is correct (let me know if they are both wrong)?

Example 1:

 public class OrderController { // Injected Repositories private readonly IProductRepository _productRepository; // Called by UI public void AddProduct(int productId) { Order order = ...; // Persisted Order Product product = _productRepository.GetProduct(productId); order.AddProduct(product); } } 

The controller creates an instance of the product itself and adds it using the method:

 void AddProduct(Product product) { productList.Add(product); } 

Example two:

 public class OrderController { // Injected Repositories private readonly IProductRepository _productRepository; // Called by UI public void AddProduct(int productId) { Order order = ...; // Persisted Order order.AddProduct(productId, _productRepository); } } 

In the Order domain model, there is a product repository transferred to them, and it receives the Product and adds it:

 Product AddProduct(int productId, IProductRepository productRepository) { Product product = productRepository.GetProduct(productId); productList.Add(product); return product; } 

Currently, I came for the first example, because your domain model should never call the service method inside, however, recently I have seen several examples that use my second example, and it looks neat. It seems to me that Example 1 borders on anemia. Example 2 would move the whole logic of adding a product to the domain model itself.

+5
source share
2 answers

The second horror ...

Adding a product to an order should not contain a repository on its signature, since the repository is not part of the domain.

I tend to go first.

+2
source

Yes buddy, the first is better ...

As if we were thinking in the form of objects ...

Adding a product to the list has nothing to do with the product repository, it should only accept the product.

+1
source

Source: https://habr.com/ru/post/918440/


All Articles