问题描述
我有一个函数返回相同类型的对象(查询结果),但没有任何属性或方法。为了有一个共同的类型,我使用一个空的接口作为返回类型和实现两者。当然听起来不正确。我只能控制自己,坚持希望有一天这些类将有一些共同点,我会把这个共同的逻辑移到我的空白界面。然而,我不满足于思考是否应该有两种不同的方法,有条件地接下来。那会是一个更好的办法吗?
我也被告知.NET Framework使用空接口进行标记。
我的问题是:空界面是设计问题的强烈征兆还是被广泛使用?
编辑:对于有兴趣的人,我后来发现功能语言中的歧视工会是我正在尝试实现的完美解决方案。 C#对这个概念似乎并不友好。
编辑:我写了一个,详细解释问题和解决方案。
尽管现在似乎存在一种设计模式(现在已经提到了标记界面),但我认为这种做法的使用是代码气味的指示(大部分时间在至少)。
由于@ V4Vendetta发布,有一个静态分析规则是目标:
是引用的MSDN推荐:
这也反映了Critique已经发布的维基百科链接的部分。
I have a function that returns same kind of objects (query results) but with no properties or methods in common. In order to have a common type I resorted using an empty interface as a return type and "implemented" that on both.
That doesn't sound right of course. I can only console myself by clinging to hope that someday those classes will have something in common and I will move that common logic to my empty interface. Yet I'm not satisfied and thinking about whether I should have two different methods and conditionally call next. Would that be a better approach?
I've been also told that .NET Framework uses empty interfaces for tagging purposes.
My question is: is an empty interface a strong sign of a design problem or is it widely used?
EDIT: For those interested, I later found out that discriminated unions in functional languages are the perfect solution for what I was trying to achieve. C# doesn't seem friendly to that concept yet.
EDIT: I wrote a longer piece about this issue, explaining the issue and the solution in detail.
Although it seems there exists a design pattern (a lot have mentioned "marker interface" now) for that use case, i believe that the usage of such a practice is an indication of a code smell (most of the time at least).
As @V4Vendetta posted, there is a static analysis rule that targets this:http://msdn.microsoft.com/en-us/library/ms182128(v=VS.100).aspx
This is the quoted MSDN recommendation:
This also reflects the Critique section of the already posted wikipedia link.
这篇关于空界面是否有臭味?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!