1
\$\begingroup\$

I have a Product entity and a ProductCategory entity. Given the Product entity, my application checks the database via a repository to see if the ProductCategory already exists. If the category is not found in the database, then the application should persist it.

Currently, I have this code in the service layer as follows:

public class ProductCategoryMapper implements DataMapper<ProductCategory> {

    @NonNull
    private final ProductCategoryRepository categoryRepository;

    @Override
    public void map(Product product) {
        ProductCategory category = productCategoryRepository.findByProductTagAndMake(product);

        if (category == null) {
           category = productCategoryRepository.save(new ProductCategory(product.getTag(), product.getMake()));
        }
        product.setProductCategory(category);
    }
}

But should this method be in the Product class as:

public void mapCategory(); // or perhaps setCategory();

This seems to be better OO but then the Product entity would have a reference to the repository (which I think is bad from a design / DDD perspective b/c the entity knows about repositories). Should the code stay in the service layer, be moved to the entity, or is there some other option?

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

It appears that this Product entity is meant to be a POJO. POJOs should be responsible only for holding the relevant data in memory to be accessed by, and possibly manipulated by, someone else.

The second you put in logic that is not directly related to the POJO, such as persistence, the flexibility of your application drops like a stone. You will be unable to use this POJO in other contexts where the repository will not be relevant, or worse, when this comes from a different repository altogether (it does happen!).

\$\endgroup\$
1
\$\begingroup\$

In DDD, an aggregate is composed of a root entity (the Product) and one or more child entities (the ProductCategory).

Business logic that creates an aggregate is usually put into a Factory. The factory implementation would then be one that calls into the ProductCategoryRepository. That is, the setCategory method (or similar) would belong to the ProductFactory class.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.