Object-oriented – When to use interfaces (unit testing, IoC?)

dependency-injectioninterfacesobject-oriented

I suspect I've made a schoolboy error here, and am looking for clarification. A lot of the classes in my solution (C#) – dare I say the majority – I've ended up writing a corresponding interface for. E.g. an "ICalculator" interface and a "Calculator" class that implements it, even though I'm never likely to replace that calculator with a different implementation. Also, most of these classes reside in the same project as their dependencies – they really only need to be internal, but have ended up being public as a side-effect of implementing their respective interfaces.

I think this practice of creating interfaces for everything stemmed from a few falsehoods:-

1) I originally thought that an interface was necessary to create unit test mocks (I'm using Moq), but I've since discovered that a class can be mocked if its members are virtual, and it has a parameterless constructor (correct me if I'm wrong).

2) I originally thought an interface was necessary to register a class with the IoC framework (Castle Windsor), e.g.

Container.Register(Component.For<ICalculator>().ImplementedBy<Calculator>()...

when in fact I could just register the concrete type against itself:

Container.Register(Component.For<Calculator>().ImplementedBy<Calculator>()...

3) Using interfaces, e.g. constructor parameters for dependency injection, results in "loose coupling".

So have I gone mad with interfaces?! I'm aware of the scenarios where you would "normally" use an interface, e.g. exposing a public API, or for things like "pluggable" functionality. My solution has a small number of classes that fit such use cases, but I wonder if all the other interfaces are unnecessary, and should be removed? Regarding point 3) above, won't I be violating "loose coupling" if I was to do this?

Edit:- I'm just having a play with Moq, and it seems to require methods to be public and virtual, and have a public parameterless constructor, in order to be able to mock them. So it looks like I can't have internal classes then?

Best Answer

In general, if you make an interface which only has one implementor, you're just writing things twice and wasting your time. Interfaces alone do not provide loose coupling if they're tightly coupled to one implementation... That said, if you want to mock these things in unit tests, that's usually a great sign that you'll inevitably need more than one implementor in real code.

I would consider it a bit of a code smell if nearly all your classes have interfaces though. That means they're almost all working with one another in one way or another. I would suspect that the classes are doing too much (since there's no helper classes) or you've abstracted too much (oh, I want a provider interface for gravity since that might change!).