简体   繁体   中英

Should I get other Aggregate value from application service or entity?

I have Inventory, Catalog, and Sales bounded contexts.

I have this invariant:

When creating catalog, we cannot sell more than what we have in Inventory

class CatalogApplicationService {
    void createCatalog(ProductId productId, int numToSell) {
        ProductValue pv = productService.byId(productId)
        // Catalog constructor will validate numToSell againts pv.numAvailable
        Catalog c = new Catalog(pv, numToSell)
        catalogRepository.save(c)
    }
}

class Catalog {
    Catalog(ProductValue pv, int numberToSell) {
        if (pv.numAvailable < numberToSell) throw new IllegalArgumentException();
        setSku(pv.sku);
        setAmount(numberToSell);
    }
}

or should I pass along the service into Catalog

class CatalogApplicationService {
    void createCatalog(ProductId productId, int numToSell) {
        Catalog c = new Catalog(productService, numToSell)
        catalogRepository.save(c)
    }
}

class Catalog {
    Catalog(ProductService productService, int numberToSell) {
        ProductValue pv = productService.byId(productId)
        if (pv.numAvailable < numberToSell) throw new IllegalArgumentException();
        setSku(pv.sku);
        setAmount(numberToSell);
    }
}

You should not inject services inside your aggregates ( Catalog ) but pass the data to them, in order to keep them as clean as possible, without unnecessary dependencies.

Also, you should use the ubiquitous language (UL) throughout your code. For example, throwing a generic IllegalArgumentException doesn't seem to be from from your UL.

Verifying a business logic is generally done at the Service layer. Models should be kept as only containing data, rather than logic. So, your first solution is advised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM