Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which of these examples represent correct use of DDD?

I've been working with DDD for a few months now and I've come across a few things I'm unsure of.

Take the simplistic example of adding a Product to an Order object. From our Controller, we'd have an int passed via the UI which represents a Product in the database. Which of the following two examples is correct (let me know if they're both wrong)?

Example One:

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 instantiates the Product itself and adds it in via 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);
    }
}

The Order domain model has the injected product repository passed to it and it gets the Product and adds it:

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

    return product;
}

I've currently gone for the first example, because your Domain Model should never call a service method internally, however I've seen a few examples lately that use my second example and it does look tidy. It seems to me that Example One is verging on Anaemic. Example Two would move all the Product addition logic into the Domain Model itself.

like image 319
djdd87 Avatar asked Oct 25 '22 03:10

djdd87


1 Answers

Second one is horrible...

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

I tend to go with the first one.

like image 77
Aliostad Avatar answered Nov 15 '22 07:11

Aliostad