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:-
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).I originally thought an interface was necessary to register a class with the IoC framework (Castle Windsor), e.g.
Container.Register(Component.For().ImplementedBy()...
when in fact I could just register the concrete type against itself:
Container.Register(Component.For<Calculator>().ImplementedBy<Calculator>()...
- 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?