views:

151

answers:

5

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?

+2  A: 

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.

Slavo
Mocking isn't the only reason to program to an interface. The other reason is, that I may not want to take a direct dependency on a FileSystemWatcher in case I want to swap it out with another implementation later.Also raising events from a mock is only possible (with Moq at least - as far as I remember) if they are declared as virtual in the original class since it needs to be able to override them to do the job.
Thorsten Lorenz
Yes, you are right. But from what I see in your question, in your case mocking is the only reason. Microsoft have decided that they don't want to give you a way to implement a FileSystemWatcher. There's just one implementation and that's part of their design.
Slavo
@ "TypeMock, then you can even mock static and sealed classes"TypeMock seems to try to give solutions to test code that is inherently hard to test. Instead of resorting to these solutions I would prefer to write code in a way, were such heavy machinery (as far as I understand they resort to reflection and other tricks to make it happen) is not needed.
Thorsten Lorenz
All mocking frameworks resort to reflection (and inherit from the mocked object), TypeMock uses profiling on the CLR level and emits code that mimics the mocked object's behavior. All I'm saying is that easy-to-mock is not equivalent to good design. Easy-to-test is different.
Slavo
Also, don't misunderstand me. I'm not saying Microsoft's design is perfect. But an interface for each class? Come on!
Slavo
+3  A: 

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.

Mark Seemann
A: 

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.

Kerido
+5  A: 

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.

LBushkin
What I mean exactly!
Slavo
A: 

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.

Ruben