作为练习,我正在尝试使用 DDD 和干净的代码构建一个小型示例应用程序:
通过应用聚合不应包含对其他聚合实体的引用,而只是它们的 ID 的规则,我发现自己在服务层中有这种逻辑:
public class StockService implements StockServicePort {
private final StockRepo stockRepo;
private final CategoryRepo categoryRepo;
private final FinhubPort finhubPort;
public static final String STOCK_NOT_FOUND_MESSAGE = "Stock not found, id: ";
@Override
public StockWithExternalData getStockById(String stockId) {
final Stock existingStock = stockRepo.findStockById(stockId);
if (existingStock == null) {
throw new StockNotFoundException("Stock requested not found, id: " + stockId);
}
final BigDecimal externalPrice = finhubPort.getStockPriceByName(existingStock.getName());
final Category category = categoryRepo.findCategoryById(existingStock.getCategoryId() == null ? "-" : existingStock.getCategoryId()); // is this OK ?
String categoryName = "not present";
if(category != null) {
categoryName = category.getName();
}
return new StockWithExternalData(existingStock.getUuid(), existingStock.getName(), categoryName, existingStock.getValue(), externalPrice);
}
@Override
public String addStock(NewStockCommand newStockCommand) {
final Category category = this.categoryRepo.findCategoryByName(newStockCommand.getCategoryName()); // is this OK ?
String categoryId = null;
if(category != null) {
categoryId = category.getUuid();
}
final Stock stock = new Stock(newStockCommand.getName(), newStockCommand.getValue(), categoryId);
this.stockRepo.save(stock);
return stock.getUuid();
}
加载类别的逻辑,以确保它存在并检索 id,应该在这里吗?
据我所知,这种逻辑不应该存在于模型类中,所以服务层,也就是应用层,似乎是它的地方,但我不太确定,想问你在这种情况下的最佳实践。
免责声明:我不认为这个问题是“基于意见”的,我想问的是在这种情况下 DDD“规则”是什么,以及根据 DDD 是否可以认为这种逻辑是合适的。