在我的应用程序中,我正在处理一个包含IMyInterface
个实例的列表.不是全部,但其中一些in addition也实现了IAnotherInterface
.请注意,IAnotherInterface
不是从IMyInterface
派生出来的.遵循单一责任原则,我有一个单独的类,它通过Process
方法处理IMyInterfaces
个实例.现在我正在为设计 Select 而苦苦挣扎,无论是
- 签名应该是
Process(IEnumerable<IMyInterface> items)
,我在此方法中筛选出IAnotherInterface
- 或者签名应该是
Process(IEnumerable<IAnotherInterface> items)
,这意味着过滤必须由"客户端"在处理方法之外进行.
为了更清楚地说明这一点,我在两个代码选项之间苦苦挣扎:
// alternative 1:
List<MyInterface> items = GetItems(); // code not shown here
foreach(var item in items)
{
// do some other processing before, not shown here
// pass items to Process(IEnumerable<IMyInterface> items)
myProcessor.Process(items);
// do some other processing afterwards, not shown here
}
// or alternative 2:
List<MyInterface> items = GetItems(); // code not shown here
foreach (var item in items)
{
// do some other processing before, not shown here
// pass items to Process(IEnumerable<IAnotherInterface> items)
// -> need to filter first
var filteredItems = filterForIAnotherInterface(items);
myProcessor.Process(filteredItems);
// do some other processing afterwards, not shown here
}
Select 一个而不是另一个,有什么好的理由吗?我自己的 idea 是,备选方案1更容易用于客户端,但Process
方法必须进行过滤,这在其主要责任之外增加了某种额外的责任.另一方面,我认为备选方案2在某种程度上降低了处理流水线的可读性.