I have some factory that's responsible to build Product entity. To build the Product it's necessary to retrieve all entities from a data source that should be associated with Product.
class ProductFactory(
private val productRepository: ProductRepository,
private val shopRepository: ShopRepository,
private val categoryRepository: CategoryRepository,
private val tagRepository: TagRepository
) {
fun build(action: CreateProductDTO): Product {
val product = Product.Builder()
val shop = shopRepository.findById(action.shopId)
product.setShop(shop)
val tags = tagRepository.findAllById(action.tags)
product.setTags(tags)
val category = categoryRepository.findById(action.categoryId)
product.setTaxon(taxon)
return productRepository.save(builder.build())
}
}
Personally I don't like the code above because of interface segregation principle violation at least. ProductFactory can access to all methods of the repositories but should not supposed to do this.
I have a thought to create some kind of DAL called Storage that could be used for specific business operation such as product creation. For example:
interface Storage {
fun findShopById(id: Long): Optional<Shop>
fun findCategoryById(id: Long): Optional<Category>
fun findAllTagsById(ids: Iterable<Long>): List<Tag>
fun save(product: Product)
}
Any suggestions?