为什么.Net框架中的每个类没有对应的接口?

发布于 2024-08-23 19:02:34 字数 1450 浏览 2 评论 0原文

自从我开始以测试/行为驱动的方式进行开发以来,我很欣赏能够模拟每个依赖项的能力。

由于模拟框架如 Moq 在模拟接口时效果最佳,我现在实现一个接口对于我创建的几乎每个类,我很可能最终都必须在测试中模拟它。 无论如何,对接口进行编程是一种很好的做法。

有时,我的类依赖于.Net 类(例如FileSystemWatcher、DispatcherTimer)。在这种情况下,如果有一个接口就太好了,这样我就可以依赖 IDispatcherTimer,能够向它传递一个模拟并模拟它的行为,以查看我的被测系统是否正确反应。

不幸的是,上面提到的两个类都没有实现这样的接口,所以我不得不求助于创建适配器,它除了继承原始类并符合一个接口之外什么也不做,然后我就可以使用它了。

这是 DispatcherTimer 和相应接口的这样一个适配器:

 using System;
using System.Windows.Threading;

public interface IDispatcherTimer
{
    #region Events

    event EventHandler Tick;

    #endregion

    #region Properties

    Dispatcher Dispatcher { get; }

    TimeSpan Interval { get; set; }

    bool IsEnabled { get; set; }

    object Tag { get; set; }

    #endregion

    #region Public Methods

    void Start();

    void Stop();

    #endregion
}

/// <summary>
/// Adapts the DispatcherTimer class to implement the <see cref="IDispatcherTimer"/> interface.
/// </summary> 
public class DispatcherTimerAdapter : DispatcherTimer, IDispatcherTimer
{
}

虽然这不是世界末日,但我想知道为什么 .Net 开发人员不花时间让他们的类从一开始就实现这些接口。这让我很困惑,尤其是因为现在微软内部大力推动良好实践。

有谁有任何(可能是内部的)信息为什么存在这种矛盾?

Since I started to develop in a test/behavior driven style, I appreciated the ability to mock out every dependency.

Since mocking frameworks like Moq work best when told to mock an interface, I now implement an interface for almost every class I create b/c most likely I will have to mock it out in a test eventually.
Well, and programming to an interface is good practice, anyways.

At times, my classes take dependencies on .Net classes (e.g. FileSystemWatcher, DispatcherTimer). It would be great in that case to have an interface, so I could depend on an IDispatcherTimer instead, to be able to pass it a mock and simulate its behavior to see if my system under test reacts correctly.

Unfortunately both of above mentioned classes do not implement such interfaces, so I have to resort to creating adapters, that do nothing else but inherit from the original class and conform to an interface, that I then can use.

Here is such an adapter for the DispatcherTimer and the corresponding interface:

 using System;
using System.Windows.Threading;

public interface IDispatcherTimer
{
    #region Events

    event EventHandler Tick;

    #endregion

    #region Properties

    Dispatcher Dispatcher { get; }

    TimeSpan Interval { get; set; }

    bool IsEnabled { get; set; }

    object Tag { get; set; }

    #endregion

    #region Public Methods

    void Start();

    void Stop();

    #endregion
}

/// <summary>
/// Adapts the DispatcherTimer class to implement the <see cref="IDispatcherTimer"/> interface.
/// </summary> 
public class DispatcherTimerAdapter : DispatcherTimer, IDispatcherTimer
{
}

Although this is not the end of the world, I wonder, why the .Net developers didn't take the minute to make their classes implement these interfaces from the get go. It puzzles me especially since now there is a big push for good practices from inside Microsoft.

Does anyone have any (maybe inside) information why this contradiction exists?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

一袭白衣梦中忆 2024-08-30 19:02:34

接口非常有用,并且不幸的是,.NET 类库中存在一些遗漏,其中一个或两个接口可以使事情变得更清晰或更简单。

然而,你必须从另一个角度去思考。 接口是一种契约。接口代表一种协议,其中契约的使用者和实现者定义他们想要如何交互。对于类来说当然也是如此,但是接口被视为一种更正式且不可变的契约形式。 您不希望界面不断变化。界面之所以有用,正是因为它们的稳定性。

话虽如此,创建一个简单地复制类的公共接口的接口并不一定会创造价值。特别是如果接口不太可能有多个实现者,或者接口的解耦不能创造明确的价值。事实上,您可能会争辩说,过早创建接口可能是有害的,因为它锁定了可能难以理解或不能清楚地捕获抽象的接口。仅仅因为模拟作为一种实践与接口配合得很好,并不足以成为为每个类创建接口的充分理由。

在您引用的示例中,尚不清楚界面是否会创造超出您对更容易模拟的愿望的有意义的价值。请记住,添加到 .NET BCL 中的每个附加类型都会使学习曲线变得更加陡峭 - 更多类型意味着需要学习和理解更多内容。

最后,为了直接解决您的问题,Microsoft 必须决定在每个版本中向 .NET 投入多少时间和精力。每个功能和每个类型都必须进行设计、实现、记录、测试、维护等。由于功能不是免费的,因此必须有令人信服的理由来实施它们,以克服巨大的成本障碍。推迟 .NET 的发布来添加可能永远不会广泛有用(甚至可能有害)的接口可能并不是大多数开发人员所希望的。

Interfaces can be very useful, and it's certainly unfortunate there are omissions in the .NET class libraries where an interface (or two) could have made things cleaner or simpler.

However, you have to think about it from another point of view. An interface is a contract. Interfaces represent an agreement in which consumers of a contract and implementers define how they want to interact. This is of course also true of a class, but an interface is viewed as a more formal and immutable form of a contract. You don't want interfaces to constantly be changing. Interfaces are useful precisely because of their stability.

Having said that, creating an interface that simply duplicates the public interface of a class doesn't necessarily create value. Especially if there are unlikely to be multiple implementers of the interface or if the decoupling of the interface doesn't create clear value. In fact, you could argue that premature creation of interfaces can be harmful because it locks in interfaces that may be poorly understood or which don't cleanly capture an abstraction. Just because mocking, as a practice, works well with interfaces is not a compelling enough reason to create an interface for every class.

In the examples you cite, it's unclear that an interface would create meaningful value beyond your desire for easier mocking. Keep in mind, every additional type that's added to the .NET BCL makes the learning curve that much steeper - more types means more things to learn and understand.

Finally, to address your question directly, Microsoft has to make decisions about how much time and effort to invest into .NET at every release. Every feature and every type has to be designed, implemented, documented, tested, maintained, and so on. Since features are not free, there has to be a compelling reason to implement them in order to overcome the large cost barrier. Delaying the release of .NET to add interfaces that may never be broadly useful (and perhaps even harmful) is not probably what most developers would prefer.

人│生佛魔见 2024-08-30 19:02:34

这是一个古老的讨论,TDD 认为 BCL 中的 Seams 太少,而 Microsoft 对他们提供的 Seams 往往非常保守。许多 BCL 实现严重依赖内部密封类,这确实损害了可测试性

我真诚地相信,.NET 的第一个版本从未关注过可测试性,但后来 Microsoft 意识到了这个问题。然而,意识到这个问题并不等于对此采取了足够的措施。

虽然它已经变得更好,但微软反对提供更开放的 BCL 的最大论点是,它给他们的开发工作带来了一些负担:

  • 他们必须确保界面的每个消费者都不会违反里氏替换原则。他们的论点是,这样做需要额外的测试工作。
  • 他们希望确保不会因为发布未经深思熟虑的 API 而将自己陷入困境。这里的论点是,一旦某种类型在 BCL 中可用,由于向后兼容性的原因,就很难将其删除。

我并不是说我完全同意这些论点,但这些是 Microsoft 最常提供的论点。

It's an old discussion that TDDers think that there are too few Seams in the BCL, while Microsoft tend to be very conservative with the Seams they provide. Many BCL implementations rely heavily on internal and sealed classes, which really hurts testability.

It's my sincere belief that testability was never on the radar for the first versions of .NET, but later, Microsoft has become aware of the issue. However, being aware of the issue doesn't equal doing enough about it.

While it has become better, Microsoft's biggest argument against providing a more open BCL is that it places several burdens on their development efforts:

  • They have to make sure that each consumer of an interface doesn't break the Liskov Substitution Principle. Their argument is that there's an additional testing effort involved in doing that.
  • They want to make sure that they don't paint themselves into a corner by releasing an API that isn't well thought-through. The argument here is that once a type is available in the BCL, it's very hard to remove because of backwards compatibility reasons.

I'm not saying that I agree completely with these arguments, but those are the ones most commonly provided by Microsoft.

勿忘初心 2024-08-30 19:02:34

接口代表每个实现类都同意的契约。它们是一种管理抽象的方法,也是用于构建面向对象系统的语言工具的一部分。如果引入接口的唯一原因是为了能够轻松模拟类,那么接口就不应该存在。模拟是一个仅对系统开发人员有意义的概念。类不能被模拟这一事实并不意味着设计不好。如果我们遵循相同的逻辑,那么为什么我们需要 seal 关键字呢?为什么你需要阻止某人继承,为什么你要把一个方法设置为非虚拟方法来停止重写?因为这是面向对象设计的一部分。而且您不会根据模拟框架的能力来创建设计。简而言之,为每个类提供一个接口是很荒谬的。

我仍然不明白为什么你不能直接模拟一个类而你需要一个接口。除非它是密封的或静态的,否则它应该可以工作。

PS如果你使用TypeMock,那么你甚至可以模拟静态和密封类。

Interfaces represent contracts that each implementing class agrees upon. They are a way to manage abstraction and part of the tools of the language used for building object-oriented systems. If the only reason to introduce an interface is to easily be able to mock a class, then the interface should not be there. Mocking is a concept only meaningful to the developers of the system. The fact that a class cannot be mocked is not a sign for a bad design. If we follow the same logic, then why do we need the sealed keyword? Why would you need to stop someone from inheriting, why would you make a method non-virtual to stop overriding? Because that's part of Object-Oriented Design. And you don't create the design based on the abilities of mocking frameworks. In short, having an interface for each class would be ridiculous.

I still could not understand why you cannot mock a class directly and you need an interface. Unless it is sealed or static, it should work.

P.S. if you use TypeMock, then you can even mock static and sealed classes.

浮生面具三千个 2024-08-30 19:02:34

默认情况下不使用接口的一个主要原因是您的 API 面向未来。扩展接口是不可能的。您只能创建新接口。这意味着您将获得 IFileWatcher1、IFileWatcher2、IFileWatcher3(只需查看 COM 即可看到其实际情况)。这极大地污染了API。类(抽象类和非抽象类)可以扩展。

另外,如果您不希望依赖于 FileSystemWatcher,那么首先创建这样的依赖项可能不是一个好主意(无论是通过 FileSystemWatcher 还是 IFileSystemWatcher4)。为此目的提供您自己的适配器,您可以自由地为其提供接口。

One major reason for not using interfaces by default is future proofing your API; it is impossible to extend an interface. You can only create new interfaces. This means that you'd get IFileWatcher1, IFileWatcher2, IFileWatcher3 (just look at COM to see this in action). This greatly pollutes an API. Classes (abstract and non-abstract) can be extended.

Also, if you don't want a dependency on e.g. a FileSystemWatcher, it's probably not a good idea anyway to create such a dependency in the first place (whether this is through the FileSystemWatcher or IFileSystemWatcher4). Provide your own adapters for this purpose, which you are free to provide interfaces for.

芸娘子的小脾气 2024-08-30 19:02:34

接口确实有一个弱点——虚函数表。对于每个接口方法/属性,系统在特殊的内存块(类的虚拟表)中保留一个指针。这使得函数调用变慢并消耗内存。因此,您应该只使用可以存在不同实现的接口。否则,您就会损害性能。

Interfaces do have a weakness - virtual function tables. For every interface method/property the system reserves a pointer in the special block of memory - the class's virtual table. This makes function calls slower and consumes memory. So you should only use interfaces where different implementation can exist. Otherwise, you're compromising performance.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文