注入多个接口是否违反 SOLID?
Inject multiples interfaces is against SOLID?
我得到以下 class:
public MealService( IFoodRepository foodRepository,
IOrderRepository orderRepository,
IDishListRepository dishListRepository)
{
_inputValidator = inputValidator;
_foodRepository = foodRepository;
_orderRepository = orderRepository;
_dishListRepository = dishListRepository;
}
...然后,这里有一些代码
在过程结束时,我做:
private async Task<Order> CreateOrderAsync(int dayTime, List<Item> items)
{
Order order = new Order();
DishList dl;
Food food;
foreach (Item it in items)
{
dl = await _dishListRepository.GetAsync(dayTime, it.DishType);
food = await _foodRepository.GetAsync(dl.FoodId);
it.Food = food.Name;
order.Items.Add(it);
}
await _orderRepository.AddAsync(order);
return order;
}
我是否违反单一责任原则(SOLID 中的 'S')?我的意思是,将太多接口注入 class 是否意味着 class 有太多责任?
提前致谢。
答案很可能是肯定的。通常过多的参数是典型的代码异味。请参阅 Uncle Bob's Clean Code 中的第 3 章。他用了 4 页的篇幅来阐述这个主题。这是来自那里的简短引述:
The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification -- and then shouldn't be used anyway.
我得到以下 class:
public MealService( IFoodRepository foodRepository,
IOrderRepository orderRepository,
IDishListRepository dishListRepository)
{
_inputValidator = inputValidator;
_foodRepository = foodRepository;
_orderRepository = orderRepository;
_dishListRepository = dishListRepository;
}
...然后,这里有一些代码
在过程结束时,我做:
private async Task<Order> CreateOrderAsync(int dayTime, List<Item> items)
{
Order order = new Order();
DishList dl;
Food food;
foreach (Item it in items)
{
dl = await _dishListRepository.GetAsync(dayTime, it.DishType);
food = await _foodRepository.GetAsync(dl.FoodId);
it.Food = food.Name;
order.Items.Add(it);
}
await _orderRepository.AddAsync(order);
return order;
}
我是否违反单一责任原则(SOLID 中的 'S')?我的意思是,将太多接口注入 class 是否意味着 class 有太多责任?
提前致谢。
答案很可能是肯定的。通常过多的参数是典型的代码异味。请参阅 Uncle Bob's Clean Code 中的第 3 章。他用了 4 页的篇幅来阐述这个主题。这是来自那里的简短引述:
The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification -- and then shouldn't be used anyway.