Ok, I may resort to a tad ranting here, so let me apologize in advance, but I'm really curious if others find this pattern annoying too (and I wonder if it is a justifiable pattern)…
So, after just looking at a particular question [1], I noticed that almost all of the responses suggested creating an interface for injecting a mock in some test code.
I don't mind using interfaces, and sometimes they can really help in static typed languages like C# and Java… but I do mind seeing interfaces for almost every class in a system(or in general being used where they aren't really needed).
I have 2 major problems with using an interface when it isn't called for:
UPDATE: a few quotes that share the concern:
From http://blog.ploeh.dk/2010/12/02/InterfacesAreNotAbstractions.aspx
Do you extract interfaces from your classes to enable loose coupling? If so, you probably have a 1:1 relationship between your interfaces and the concrete classes that implement them. That’s probablynot a good sign, and violates the Reused Abstractions Principle (RAP) [3].
Having only one implementation of a given interface is a code smell.
From http://martinfowler.com/bliki/InterfaceImplementationPair.html
Using interfaces when you aren't going to have multiple implementations is extra effort to keep everything in sync.Furthermore it hides the cases where you actually do provide multiple implementations.
Dependency Inversion Principle (DIP) never states that we should depend on explicit interfaces... In .NET, though, there are a number of abstraction forms that we can rely on, explicitly. We have the obvious interfaces and base classes (abstract or not) – but we also have constructs like delegates and lambda expressions, and even the simple types that are built into the base class library
Now… if you are testing something, and you create an interface JUST TO ALLOW MOCKING… this seems to be adding a layer of minor headaches for no real benefit. What does creating the interface do that just overriding the class won't do? What is so bad about having a mock that merely overrides some methods of the single implementation class?
I guess it should be no surprise then that I much prefer Java's default virtual methods (ie requiring a final keyword to have a method that CAN'T be overriden) to C#'s default final methods… and I also tend to avoid the final keyword on methods and classes too. Introducing virtual methods are not ideal, but less-intrusive approach to support mocking compare to duplicated interfaces.
So is there something to using interfaces that I am missing? Is there some hidden benefit of using an interface when you have 1 version of a class and no immediate need to create an interface? What could be justifications, why some developers insist to create interface for each class?
Interfaces are useful in order to add a level of abstraction early on in the design process. It will benefit the modularity of your code. If you have a big enough project (one that warrants using mocking) interfaces are useful, though for small projects this is most likely overkill. They can be used more than they need to be certainly, but if you take to heart the following guidelines you will know when to use inheritance and when to use an interface. Your code reusability and scalability will increase greatly when interfaces are used where appropriate!
The old explanation of when to inherit works nicely:
Is a - inheritance
Your class is a subclass of a more generalized class, e.g. HouseCat
inherits from Feline
because a house cat "is a" feline.
Has a - member field
A LittleGirl
has a cat, so obviously she should not
be a subclass to HouseCat
(she is not a cat). It is
best that she "has a" HouseCat
member field.
class LittleGirl
{
int age;
string name;
HouseCat pet;
}
Performs - interface
Interfaces should be used when a class or group of classes all have similar functionality, but when there is no obvious line of inheritance. Think of them as a certificate that says "this object performs this functionality."
For example, a HouseCat
might inherit from Feline, but implement the ICanHasCheeseburgers
(or ICanHazChzbrgrsPlz
) interface. That way you have a BurgerJoint class with a method public CheeseBurger Serve(ICanHasCheeseburgers patron)
and be able to pass either Humans
or HouseCats
to the Serve
method in order to feed them a Cheeseburger
.
This is useful because HouseCat
does not inherit from Person
nor vice versa. However, they both perform acts involving CheeseBurgers
.
~ William Riley-Land
A big headache with interfaces in Java and C# is that they give you so few options to evolve your contract. E.g.:
interface ILogSink {
Log(DateTime timestamp, string message);
}
If you define this in a framework and have a lot of different external consumers that all implement this interface you cannot change it without breaking their implementation. If you need to change it in the next version, you end up with something like:
interface ILogSinkVersion2 {
Log(DateTime timestamp, string message, CultureInfo culture);
}
If you use a base class on the other hand, you can start out with:
class LogSink {
void Log(DateTime timestamp, string message);
}
And evolve it to:
class LogSink {
[Obsolete("Please include CultureInfo using Log(DateTime, string, CultureInfo)")]
virtual void Log(DateTime timestamp, string message) {
}
virtual void Log(DateTime timestamp, string message, CultureInfo culture) {
// Call old method for old implementations:
Log(timestamp, message);
}
}
This way you can evolve your code without forcing every implementation of the contract to consume your changes immediately.
Update: This is not a big deal if you sit on your own island and own all your code. However if you maintain a framework interface like log4net's ILog interface or .NET frameworks IDisposable interface, you need a quite good reason to add or change methods, since it will affect a few thousand implementations throughout the world.
If you have one class I can understand your hesitation with interfaces. According to Robert Martin's book Agile principles, patterns, and practices in C# [1]. In the book he describes the Dependency Inversion Principle. I don't believe he invented it but he's who made it click for me.
Basically the more you depend on interfaces the less fragile your software. This is an ideal though. I say break it where it makes sense. If you're not using interfaces more often than you are then there may be other problems. For example, just because you have different classes doesn't mean they should all have different interfaces. The interface segregation principle states that we should break up interfaces into the most reuseable atomic components possible.
For example imagine having 100 different data access classes (each for a different kind of entity). They could have their own interfaces but what if they shared a common ICrud interface? Then you know each supports the basic CRUD methods. In this way you should be looking to add consistency and order through out your code... ideally. No one's perfect at it (and productive) but it's a good ideal to strive for.
[1] http://books.google.com/books/about/Agile_principles_patterns_and_practices.html?id=x4tQAAAAMAAJ...but have always kept quiet about it.
A few years back I took over a project that had zillions of single class implementations of a corresponding interface...in a closed system! (The API was never externally exposed.) More files, more code, more characters. WTF?
It is one of those cases where people become obsessed with 'the rule' and lose pragmatism in their designs. (Like bureaucrats becoming obsessed with the bureaucracy rather then the purpose.)
And then there is a class of coder who considers the most verbose code, the code using as many language features as possible, to be the most 'correct'.
Interfaces have their place, but it's not everywhere. Very often XP's You Aren't Going to Need It [1] principal applies.
On a side note, I cannot stand interfaces prefixed with I (E.g.: IMyInterface
). Can anyone say Hungarian Notation? (For the hair splitters, it is 'Systems Hungarian Notation', to be specific.) It is information that tooling can communicate, just like whether or not a variable has a local or member scope.
m_
? A matter of taste, I suppose. - Stu Thompson
Read about the open/closed principle [1]. Depend upon abstractions, not details. If you're depending on a concrete class, you're depending on details and there's no opportunity to change just one of two or more coupled components, you must change them all.
You say "JUST TO ALLOW MOCKING" as if it's a bad thing and then say that there's no real benefit. The benefit is in the decoupled design that allows me to use, for example, an Inversion of Control [2] container that may have aspect-oriented programming [3] features or support runtime dynamic code-composition, etc. By following these design principles, my options are always wide open. Being able to mock and perform interaction testing is one benefit I get and it happens to prove out the fact that my abstractions are aligned correctly according to the correct interaction boundaries.
When the testing via mocks goes well, it's a canary in the mineshaft that tells me whether things are designed correctly. When the testing via mocks goes poorly, I have a problem and it's usually reflected in other areas of the application, too, not just the mocks (again with the canary analogy).
Sure, sometimes you may not ever have an alternate implementation of ISomeFoo in which case it might have been a waste for that particular component. But if you ever DO need to have an alternate implementation, going and changing those 50 references to concrete PetrolSomeFoo to concrete HydrogenSomeFoo will hurt really bad, especially if someone of the changes involve other applications or integration scenarios.
I totally do NOT follow you on the files-on-the-filesystem argument. That matters so little as to be a non-argument. If your design concerns number of files on the filesystem, you might have a problem :) Or, you know what, put the ISomeFoo inside the same file as your first concrete implementation. There, 1 file.
Finally, your instinct that interfaces are smelly is not totally a bad one. But what is smelly is the statically-typed class-based languages like C#, Java, etc. that require strong interfaces (instead of, say, duck typing [4]) in order to obtain the necessary abstraction to pull off the open/closed principle.
If we had duck typing, you wouldn't need so many interfaces and this conversation would be moot.
[1] http://en.wikipedia.org/wiki/Open/closed_principleOk, I just wanted to thank everyone for all the great responses (I added comments on most of them for what I felt on each individual one)! It seems there is a strong division of people who firmly believe interface overuse is a good thing, and those who are on my side of the fence of believing they are a sign of a problem (and an antipattern).
Let me add 1 thing to all of you who seem to think creating an interface for just 1 class is a Good Thing:
Consider a class that does nothing in the constructor, except maybe set some fields and invoke some protected methods (which could then be overridden in both a mock and an alternate version of the class that some client decides they want to create). Now, how does this differ from an interface, realistically? Both are equally flexible to the client, but the class has the added benefit of being less complex. Essentially, the class is now an interface that also happens to be a default implementation.
If that clicks for you, you probably just realized why interfaces for 1 implementation bothers me so much.
Note that I am not talking about multiple inheritance... there are times where it is quite useful to be multiple things... but I say don't ANTICIPATE it... it is most likely not going to be needed... instead factor out the interface later when you see you DO need it (most IDE's have an "extract interface" refactoring tool).
There are 2 cases of interfaces being extremely useful that I can think of (off the top of my head) which I would jump on (and have) if I were going to implement such a thing:
Anyways, I'm not trying to say NEVER use interfaces... I'm trying to say evaluate it in each individual case, and try to see if there is going to be real benefit in adding the complexity to your system (there is no point in incurring unnecessary cost, right?)... like all patterns, patterns can be overused and applied when they don't actually give you any benefit, and I really believe interfaces are an overused pattern.
I completely AGREE WITH YOU!
I stated this in my answer: Mocking method results [1]
And I had to edit my answer twice to be clearer, because almost all answers suggested creating an interface to an UTILITY class. This kind of answer was even accepted. You should create an interface for testing purposes if it makes sense - which it does NOT in the context of the question.
Creating an interface is not even the biggest problem. I think the worst is to obligate a client class to inject the interface implementation when calling a simple operation. This will increase the complexity all code using that class. This is very bad. It's a hack! A BAD hack! Why is it bad?
I have rarely seen interfaces "over-used" in my experiences, but it is certaintly possible.
Knowing when to use:
are keys to good designs. You can't learn enough about this, and we can't talk enough about it. We can talk about the "fringe" cases (all 300 classes in this library have interfaces), but I think that's a waste of time. We already know that "creating interfaces just to support unit testing" (or any other "just to support.." phrases you can think of) is not the right answer.
Yet there are some simple rules (the "is-a" relationaship test comes to mind). There are also some obvious situations where interfaces are used (plug-in architectures, for example). I will offer this thought...
Most piles of code in a library (think about the 300 classes mentioned above) have some public-facing interface that is significantly less large than "the entire code", and normally less large than what the library needs to support itself. Presenting this as a series of interfaces is what you want to be thinking about. Designing these interfaces requires a different train of thought than the code design - you are thinking about the consumption of your code, not the implementation of it.
By including this thinking, and designing interfaces, you will most certaintly be rewarded in the later stages of development (assuming this is a reasonable large system with more than one developer).
I wanted to post one final response after a little more thinking. I'm preparing for the barrage of down votes I might get with this.
I think this very issue shines a bright light on the issues that can arise with static typing. Notice I'm not saying strong typing, merely static. Really, all of this nonsense about interfaces is really just us TDD [1] guys trying to be able to test each portion of our system in isolation. If we could duck type (signature based polymorphism) I guarantee you none of us would be rationalizing making those explicit interfaces.
What TDD aficionados like myself are saying is in the language I am using I need to use interfaces to get the level of decoupling I am after. I'm saying I need that decoupling to have an actual unit test, to verify 99% absolutely ;) that I have done my job. I would honestly rather just be able to use duck typing and only explicitly define an interface when I expect it to be of some use. One of the reasons I enjoy JavaScript is the ease with which I can create a mock object that looks and behaves like the real thing (as far as the injected class is concerned).
In closing allow me to summarize. I think the pain point isn't in either side's philosophy. One side is idealistic about how much decoupling they should be able to get and the other side is trying to deal with the practicality of applying such ideals in languages such as C# and Java. Both are good sides to be on. In the end, it comes down to understanding the limitations of your language and just making a judgement call on a case by case basis as to which side of the fence you'll choose to side with today.
[1] http://en.wikipedia.org/wiki/Test-driven_developmentI find that in most cases interfaces are seriously underused.
Using interfaces from the start allows you to divide behaviour and implementation. With complex applications this makes early programming a bit more complex but long term programming becomes a lot less complex.
"Another file to the system" objection is so 1980's. So what? I'd rather have 100 source files that are small, clean and easy to understand than 2-3 files that are huge and full of highly coupled code.
The objections you present are superficial. What interfaces provide is a cleaner separation from a service and something that uses the service. If I want to know what time it is, I only need to look at the watch. I don't need to see all the little wheels and springs inside. And I don't really care if the watch is on my hand or it is a Big Ben: they both share a same interface.
For me an interface should only be created when there's someone, somewhere which doesn't really care about who is implementing it as long as it's being implemented.
And that's the only place to use them, to define and agree on behaviour, any other use is probably misuse (some exception for particular cases allowed but generally speaking)
Well on a recent project, I took a plunge and used interfaces heavily. By that I mean that almost all the classes in the project implement at least one interface. Some implement 2 or more. But also the number of interfaces is far lower than the number of classes.
The possibilities of this have shocked my socks off!
Allow me to give an example. Two of the interfaces are Provider
and Receiver
.
The first methods built were two classes. One was a SymbolManager
as a Receiver
of market symbols. The other was a FileProvider
as a Provider
which is reading financial data from a file and passes it to the SymbolManager
. At first it felt cumbersome putting the methods both in the SymbolManager
and the Receiver
interface. Same for FileProvider
.
But the next requirement was to have multiple SymbolManager
s each for a different "symbol" which is a financial instrument.
And then the requirement was to feed data to them from a single "provider" which was a data broker. Well the data broker feeds many symbols so they need to be multiplexed to the proper SymbolManagers
.
So the ProviderService
implements Provider
and feeds data to multiple Receiver
s.
Next users need to send this data remotely across a network so now a ReceiverStub
implements a Receiver
and marchals the data across TCP/IP with a ProviderProxy
receiving and passing to a Receiver
.
Point is that more and more Receivers
and Providers
keep getting added AND it's very easy through configuration to connect them in various different ways.
I'm shocked at how often we keep coming up with more Provider
and Receiver
ideas.
The most power of all this, of course, is that when we add a new Provider
or Receiver
implementer, it can get connected to any other of the other existing objects just by injecting into the other object WITHOUT changing the older objects code.
In fact, it helps me to think of Interfaces as an easy way to make software operate internally similar to a "plug-in" architecture where you can add functionality to older code without changing the older code in any way.
It's nearly impossible to see the value of Interfaces until you get hit with a requirement later in a project or even after it's finished that you never accounted for when building it originally. If you made it loosely coupled you find it quick and easy to make the change usually. If not, it may be more painful and time consuming.
We have even taken this to a literal plug-in architecture by allowing users to create their own implementers of interfaces that get dynamically loaded via reflection. In fact, the GUI dynamically finds all classes in their DLL that implement certain interfaces and let's them pick from the list.
Now that I've built "loosely-coupled", pluggable architecture using interfaces, I can't imagine working the old way.
The original edict to "code to interfaces" seems to come from the GOF "Design Patterns" book. The important thing to realize from this is the interface they are talking about is not the Interface
keyword/concept as it is most often currently interpreted as. The interface as they are writing about is just the public interface as represented by some class be it abstract or otherwise.(Interface
didn't exist yet when the book was published)
Overriding some methods to provide your mock or stub is as a valid option as implementing an Interface
to do the same. The trade-offs of inheriting from the class you're going to mock or via extracting and implementing an Interface
are up to the details of the particular implementation.
Bottom line, if the interface is simplifying the test and making the implementation more complex than it needs to be, I consider it bad design... I would rather add a bit of complexity to the test and keep my implementation clean.
(ie, the interface should be simplifying the implementation, not the test).
When you are considering writing anything which is likely to be a shared resource across multiple projects, then in my opinion, you simply must use interfaces. I'll give you an example:
Where I work (in a financial firm), we have an API which allows tradable product information to be accessed from any application:
Product p = productService.lookup(ProductCodeType.TICKER, "MSFT");
A decision was made that Product
should be a class as opposed to an interface. Unfortunately, this has come to be a millstone around our necks. Why? Because Product
is not quite as simple a class as it was first supposed to be.
We have a number of implementations of the ProductService
which offer various caching strategies, static or dynamic views of the product universe. But we cannot do some very useful things which we want to do with the Product
s themselves, for example, hydrating properties in a background thread, using proxies to collect statistics, eagerly fetch and hydrate their properties, etc.
Had Product
been an interface, we would have none of these restrictions. Interface
is simply the mechanism the Java language designers used to "implement" the familiar design pattern.
(And to think I almost failed a Software Engineering exam because I had placed interfaces only on classes that required it, rather than everywhere...)
Basic rule of thumb: If you only have a single class implementing an interface, and if you can't think of another possible implementation of the interface, you don't need an interface, at least not now. You can always refactor and add an interface later, if required.
I'd argue that you should not add interfaces because they are somehow required by your testing strategy. Unit tests are the most important tool developers have (in my opinion), but they should not force a particular design. Fix the test infrastructure if it forces interfaces on your design.
You do not add the interface for allowing mocking. In reality, if you need to mock something, is because there is a dependency on an external component, and the interface is used to decoupling that dependence, which in return allows Mocking, but thats a consecuence of a better design, not a requirement for mocking.
The problem with the question you link is this:
I want to have a known result from the Helper.GetSomeData() method. Can I use a mocking framework (I've got fairly limited experience with Rhino Mocks but am open to anything) to force an expected result? If so, how?
The user needs a deterministic result, so the only solutions are mock the helper, or just hardcode the value directly.
On your concerns:
If you try to brownse the code for an interface's implementation in your project you didt't code, chances are that you probably know beforehand what the implementation is (maybe because of a previouse debug trace), or that you IDE have an 'find all references' for that interface, or better utilities if you use third party plugins (an user said in this question that Resharper has a "go to inheritor' option) I don't think is a big deal.
Adding a new file is good. Really. Separate all files and implementations in numerouses files is not a bad thing, because we have tools that take that bunch of files and organize it in a proper structured way: a project. Your real concern here is not adding a new file, but adding new simbols you need to care about ,IMHO, which add complexity to the project.
Interfaces should be used with care - don't add too much abstraction when it is not necessary! The minimalistic approach is really good thing - it help for easier walk through the code after several months when nobody remembers the big interface hierarchy
To be flexible, think "factories".
If you define and use factory methods for object creation, it doesn't matter whether you're using a class or interface to the callers.
Think about it for a minute...
Suppose you start with a class:
public class Foo {
Foo() {...} // package-access
}
and define somewhere in the same package
public Foo createFoo() { return new Foo(); }
Users can write
Foo foo = SomeFactory.createFoo();
Later you decide it would be good to use an interface so you can have alternate implementations. So you change to
public interface Foo {...}
public class SomeFooImpl implements Foo {...}
and change the factory method
public Foo createFoo() { return new SomeFooImpl(); }
This allows you to "have your cake and eat it too". The factory methods are a wee bit extra overhead, but give you flexibility later on down the pipe.
OK, now the confession: I don't regularly do this, but I'm thinking about doing it more and more. Thought I'd throw the idea out there and see who it sticks to and starts digesting them until it grows into a big blob that only Steve McQueen [1] can stop.
[1] http://en.wikipedia.org/wiki/Steve_McQueenI think the arguments that you provide against interfaces are not valid at all. For me programming is not about how many files you have in the application, or how easy it is to go to the source of something. Programming is about making things work the right way. Now, I've participated in the implementation of applications that expose extensive APIs and are used by many other developers. If I didn't use interfaces, I doubt I would be able to make users of these products happy. In short I think you are irritated by the IDE, as Roger said, not the interfaces themselves.
and you create an interface JUST TO ALLOW MOCKING
If you can mock an object, then it means that you can extend it and you have the flexibility to add additional functionality to the released product. So in fact there's no "just to allow mocking", mocking rather adds visibility to some design flaws you may have in the product. It is the same as with unit testing - only after you start doing it you realise how bad you clients felt with your product.
And finally, I also think that interfaces allow multiple inheritance in languages that otherwise don't support it. So my advice to you is to get the right tools for your IDE and don't confuse programming experience with the final result.
I would have added a comment....
For Eclipse, highlight the method and hit Ctrl-T, this will bring up the hierarchy of implementations for a method which will allow you to go to the implementation with a single click. This is especially useful with a Spring/Hibernate driving application where you want to skip all the proxies and reflection classes in debug mode.
On the broader topic of interfaces, I feel they're only needed when a factory of some sort is used, and preferably at component or application boundaries. A component that heavily uses interfaces internally and has a 1:1 interface:class ratio usually smacks of bad architecture or drinking the Spring Kool-Aid [1] (essentially the same thing). Adding an interface for the sole purpose of Mocking is injecting test code into your production code and should be avoided at all costs.
Lastly, you should note that you can extract interfaces out of a class with ease when needed with Eclipse (and probably most other major Java IDEs as well) although you might need to rename your file outside of Eclipse, refresh, and then do an extraction back to the original name. This process allows you to effectively rename the class without breaking all the links to it, which will now utilize the interface. You can also specify which methods you'd like to extract, which will quickly show you via compile time errors where you're referencing the implementation class directly.
[1] http://en.wikipedia.org/wiki/Drinking_the_Kool-AidYes. There are a billion programmers out there who've been taught design patterns so now they have to make everything fit into one of those nice neat boxes. Code's no good unless it's complicated.
By programming against interfaces you're able to switch to implementation in a central place, e.g. a factory, a builder or dependency injection, which is a good thing.
The downside is a higher complexity, so using interfaces depends on your requirements/needs. If you have a fixed implementation that yould never change, let it be.
There is something else at work here that nobody has mentioned: personality.
Developers with certain personality types love a high degree of structured craftsmanship. They like putting boxes inside of boxes. For these developers, using interfaces FEELS good, and so that makes interfaces easier to use and much more effective for them.
Developers with other personality types love problem-solving. They want the most efficient path from A to B. To them, adding anything to the code that might never be used FEELS bad, and so that makes interfaces harder to use and less effective for them.
If you love Interfaces, you will spend more time thinking about them, and your Interface designs will be better, and it will make you love Interfaces even more.
If you hate Interfaces, you will spend less time thinking about them, and your Interface designs will be weak, and that will bite you later and will make you hate Interfaces even more.
So, how you FEEL about Interfaces has a major impact on when you should use them. If you hate them, reduce your use of them, because you aren't going to do them correctly anyway. We are only human. :)
It seems to me that some of the difference in opinion here boils down to the issue of Test-Driven Development [1]. Personally, I am a great fan of TDD, but that is off-topic here, so let us skip that discussion.
The motto of TDD is Test First. You might rephrase that as Tests First. To get into the proper state of mind for TDD, you not only need to code your tests first, you should also make sure that you ensure that you think of tests as a first-order concern.
Once we have established tests as a first-order concern, the reason for the many interfaces becomes much more obvious. In Test-Driven projects many (almost all) responsibilities will have at least two implementations: the "real" implementation and the mock/test-double/fake-object. Since the "real" implementation and the test-double(s) should not share any code (otherwise you are not properly isolating your tests) it makes sense to have a interface rather than letting the test-double override all the public methods of the "real" implementation.
To summarize: Many commenters are arguing that interfaces are used incorrectly, when they are only used to facilitate mocking. But when you use a test-double, no matter if it is a autogenerated mock-object or a manually written fake, you will have created a second implementation of your contract. You might argue that the second implementation of the contract is of lower value than the "real" implementation, so that you should not allow it to influence the structure of your "real" code. But then you are actually taking issue with Test-Driven-Development, which is another (and larger) discussion.
Edit:
I love TDD, and it is patently false to try and claim an interface is needed for it. TDD just means testing first, not creating an interface for anything you use. Mike Stone
I did not claim that you need interfaces for TDD. I claimed that TDD frequently require you to create and use multiple independent implementations of the same contract: the "real" implementation and the test-doubles. My point was that this situation is exactly where using interfaces is appropriate.
[1] http://en.wikipedia.org/wiki/Test-driven_developmentInterfaces can be good for decoupling modules of your system that are at different levels of abstraction - for example, see the Separated Interface Pattern (http://martinfowler.com/eaaCatalog/separatedInterface.html). In this specific case, I can see there being value in splitting into interface and implementation, even if there is just one implementation.
For example, following Domain Driven Design [1] principles, you try to have a separate, rich, entirely "business-focused" layer. This layer may still require access to objects that come ultimately from the database. By defining a "Repository" interface with operations defined purely in domain terms within the domain layer, and then having it implemented by a class in the infrastructure layer (which knows all the data access details), you eliminate the dependency of the domain on any infrastructure code (i.e. you could happily compile your domain layer without requiring the infrastructure code to be present).
However, I do agree that introducing interfaces just to support testing, or creating them as a matter of course for every class seems very wrong.
[1] http://en.wikipedia.org/wiki/Domain-driven_designI used to use interfaces for mocking but at least in C# with rhino mocks you can get around that (you'll be making a lot of methods virtual though.). I agree that using interfaces just for this is a waste.
Another reason to use interfaces is for decoupling dependencies. Instead of one class depending on another they can both depend on an interface, one by implementing it and one by consuming it. I still use interfaces a lot for this. In a model view presenter architecture I usually have the presenter depend on an interface on the view instead of on the view class directly. This can be a very useful tool for resolving circular references between assemblies in your code too.
Interfaces are also a good tool to be more flexible in the way you order your work. If you want to implement and test high level behaviour first without getting bogged down in low-level dependencies you can just implement the low level behaviour (like persistence or writing to a file) as an interface and mock it in your tests. Later you can decide if you want to implement the interfaces you made this way or remove them completely if they're not useful anymore. Interfaces that are implemented only once and are only used within an assembly usually get removed.
Another thing to keep in mind that it's usually better to create small interfaces and implement more of them in a single class than create big monolithic interfaces. This improves decoupling and flexibility in your object design.
@Mike Stone: I often remove pieces of code that don't carry their own weight when refactoring. That includes interfaces that don't add anything useful. I agree that dummy implementations of classes as scaffolding can be better when you dont intend to use an interface in the final version. Interfaces require less typing beforehand but more refactoring to remove them when you're done. I don't always know beforehand what I intend to use though.
You're right, referring to an interface conveys less information than referring to a concrete class. But this is generally a good thing. It keeps code simpler, which is usually better. Code written against an interface is only concerned with what the interface provides, and so all the extra information about what implementation you're using is irrelevant. I usually find code easier to read if it doesn't contain irrelevant information.
To respond to the two things you don't like about interfaces:
This is a problem with modularity in general. The same thing happens when we decide to create a function somewhere instead of just writing the entire application inline within the main() method. This is a strange complaint. It seems you could use the same principle to complain about variables: e.g. you don't know what the value of a boolean variable will be at runtime, so how do you know whether to read the code in an if block?
Don't add a separate file for the interface and its implementation if it bothers you. Do this instead:
:
public interface Foo {
public void bar();
... other methods
public static class BasicImpl implements Foo {
public void bar() { ... }
... other methods
}
}
You abstract away where the implementation is coming from. This problem has a couple consequences... in an IDE, it means that when I try to browse to the source of this method being called... I get taken to an interface instead of some code that I can look at and see what is going on. This bothers me a lot, but also this is a real problem to me to hide where the implementation is coming from (sometimes it can be in non-obvious locations)
This could be considered to be a problem with your IDE. For C# editing, I use Jetbrains ReSharper, and it has a natty "Go to Inheritor" feature that takes you from a method in the interface to the implementation. I suspect that other VS addons (Visual Assist, the DevX tools, etc.) will have a similar feature.
If you're on Eclipse (I'm not), I suspect that someone will have cooked up something similar.
in an IDE, it means that when I try to browse to the source of this method being called... I get taken to an interface instead of some code that I can look at and see what is going on. This bothers me a lot, but also this is a real problem to me to hide where the implementation is coming from (sometimes it can be in non-obvious locations).
This is a problem of your IDE. With IntelliJ you don't have this problem (ctrl+alt+b).
It adds ANOTHER file to the system...
Agreed. Though, in my experience projects with "heavy interface usage" are easier to maintain.
It's your choice if you want to go via mocking in TDD or not. TDD done the mocking way necessitates some use of interfaces. However, I do agree with you to some extent and feel that sometimes intensive interfaces mean that objects that are meant to be stubbed are instead mocked, and there's a wide difference between the two [1], or it's a case of TDD gone wrong.
[1] http://martinfowler.com/articles/mocksArentStubs.htmlTo the original poster - I'm with you. But I'll qualify that:
But, with those two qualifications in mind, interfaces are way abused especially in big J2EE [2] projects. I once had to debug a problem where there were 15(!) interfaces, stubs and facades between the bit of code that called a function and the implementation of that function. And the unit tests still weren't mocked properly. Just awful.
[1] http://en.wikipedia.org/wiki/Test-driven_developmentYou asked:
What is so bad about having a mock that merely overrides some methods of the single implementation class?
The reason is simple: if you are to unit test something, it has to be done without interference of other classes' implementations. If you merely override a "production class", you could cause a situation where the test uses non-mock code - which means it could fail because of external influences (i.e. some other class' code).
Whether you agree to unit testing done this way or not is a different question - but this is why it's necessary to have something more abstract than merely overriding a production class.
And again: mocking is useful when you want to be sure, during testing, that you know exactly what input you'll be getting from external influences without needing to know their implementation details. This is extremely useful, especially when the implementations of other classes can take a long time to complete (major calculations) or require specific external software to complete (Message queues, DBs, etc. that might not be available for your unit-testing needs).
I can only see benefits. I for one never pass implementations as parameters. I only pass interfaces around. Its also useful when you are doing DI. Anyway. Who cares how a class is implement the consumer is only interested in the things it can use and an interface only gives him those things. Ok I admit it's a bit against the YAGNI principle but programming against interfaces becomes a habbit that you won't be sorry you did.
I couldn't agree more. Interfaces are like the "getters and setters" of the type system. Cruft that gets added everywhere whether it's necessary or not.
The trouble with interfaces is that they encourage inheritance and impose a hard hierarchy which makes your code brittle. Multiple inheritance? You should be using less inheritance, not more. Composition will set you free (and allow you to make all your classes abstract or final).
The mocking excuse is a red herring. Use automated specification-based testing [1] and let the machine worry about mocking. Also, if you can't create real instances of any classes for testing because their methods may have destructive side-effects or have hidden dependencies on the state of the outside world, then you have flexibility problems that testing to interfaces is only going to encourage you to ignore.
[1] http://code.google.com/p/scalacheckThe other reason for interfaces is when you want to offer maximum flexibility on implementation. That is you don't want to force the implementor to inherit from a base.
What if my class inherits from a different base? I am now forced to write a custom adapter that implements the particular base class being consumed rather than simply implementing a contract.
I think you can overuse interfaces, however the reason for using them should be to decouple the components in a system. Even in small systems tight coupling between components is not a good thing (because customers always want more).
Tightly coupling an application to any database, file system or any other external resource will only tick your customer off when you give them some outlandish quote to change accessing a database to a webservice.
I agree. I've been struggling with this question for ages now, and was going to raise a similar Stack Overflow question when I found this one.
I write a lot of Spring [1]/ Hibernate [2] applications, and if conforming to the Spring/Hibernate standard way of structuring a web application, the procedural flow is usually recommended to go from action class --> service class --> DAO [3] class, where the service and DAO classes have interfaces. So when I want to add a simple getter to get a new object/list out of the database and into my action, I have to write:
- ServiceInterface.getObject()
- ServiceImplementation.getObject()
- DAOInterface.getObject()
- DAOImplementation.getObject()
That's four changes in four different classes to add a simple getter!
If there's only one implementation per interface, I find this overkill. I still do it to remain consistent with the norm, and to remain consistent to other code in the same application which does require interfaces, but I still find it overkill.
It's little wonder languages like Ruby [4] are so loved (by some).
[1] http://en.wikipedia.org/wiki/Spring_FrameworkI think that this question points out one of the issues (flaws?) with the object oriented paradigm. I know that when I started out with OOP, I would use inheritance for everything. I would use the template pattern a lot and while this created productivity gains in the short run it would make class hierarcy headaches in the long run. In short, when I used inheritance, I would see simplicity and productivity in the short run and complexity and problems in the long run. The standard argument for using Interfaces and Object Composition.
Because of this I have moved to Interfaces and Dependency Injection [1]. Has this become my "golden hammer" solution? Maybe, at this point I cannot say for sure. It is working well so far. I do see that my objects are far less coupled, but the overall structure of my system is more complex and I find myself writing more lines of "glue" code to have my objects interact.
Perhaps this will be the issue that ushers in the next paradigm. Personally, I'm learning a functional language ( Erlang [2]) in the next year to see what other programming perspectives there are out there.
[1] http://en.wikipedia.org/wiki/Dependency_injectionSometimes I don't like having interfaces all around either, but quite frankly those two items you've mentioned are not real problems at all:
IDE don't show the implementation
Use a decent IDE, IntelliJ IDEA [1] makes this pretty easy.
You probably would have the same problem using class inheritance anyway.
Which one the running implementation again?
Adds another file to the system
If you can still count or at least perceive the amount of files in your project, probably you don't need interfaces at all in first place.
[1] http://en.wikipedia.org/wiki/IntelliJ_IDEAI agree. C# uses interfaces to replace multiple inheritance. I don't really like it much but then Microsoft forgot to call me when they were designing the language ;)
And the following is really good
Wikipedia:
One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java (other than java.lang.Object, the root class of the Java type system) must have exactly one base class; multiple inheritance of classes is not allowed. However, a Java class/interface may implement/extend any number of interfaces.
And at least in Java EJB interfaces where used for defining home and remote interfaces. A very practical way of describing which functionality will be available from outside of your VM.
Interfaces allows you to work in a higher level of abstractation. that's important if you're planning on adding more use-cases (=classes)somewhere in the future.
Use case for creating an interface when there isn't an obvious need: The interface can make it easier to understand the basics of the class (looking at all of the public methods could add too much noise).
All language features are probably used too much (when they shouldn't be used) and too little (when they should be used). Overall I think that I have seen interfaces used a little too much.
I only use interfaces as a solution of last resort. I prefer abstract base classes over interfaces because it provides the ability to abstract base (common) code into one place. Additionally Visual Studio handles base classes better than interfaces.
That aside... The interface pattern is for providing reference to a related set of data items that can exist between unrelated data models (classes). I've often seen interfaces used on related classes instead of a base class (abstract or not) and it is one of my pet peeves...
In C#, a lot of the concerns about encapsulating common use cases of interfaces and evolving interfaces by adding convenience methods can be addressed by (judicious) use of extension methods [1].
[1] http://msdn.microsoft.com/en-us/library/bb383977.aspxSome of your concern around Visual Studio not handling code navigation via base classes could be solved by using ReSharper [1]. I personally would not code against an Interface heavy solution without it.
[1] http://en.wikipedia.org/wiki/ReSharperAnother way to look at interface is to look at it from productivity point of view. And yes, it has something to do with mocking. It's far easier to distribute work among different parts of a project among multiple group members if you are purely dealing with contracts (interface). Or at least if your base class implementation is very thin, then you can use that. Otherwise, if you aren't using interface and mocking your own thin implementation to test, you are totally dependent on the actual code, and guess what, when the developer that is working on that part of the code changes it, check it in and it break your build and left for the day.... Overused, perhaps, but as with all things, there are always advantages and disadvantages, just choose your poison wisely.
Use interfaces when you want to use dynamic proxies [1] and aspect oriented programming [2], or runtime generated classes (mock objects is a particular example).
Adding interfaces is not breaking, so if your classes are not exposed outside it's OK to add them only when you'll really need it.
[1] http://java.sun.com/j2se/1.3/docs/guide/reflection/proxy.htmlI just want to list a few design principles which I strictly adhere to :-
Encapsulate what varies
Favor Composition over inheritance
Program to interface not implementation
I love design patterns; however, I truly believe they should not be overused. In the end, as Bruce Lee said, "no" technique is the best technique.
"You abstract away where the implementation is coming from. " -That's part of the point, and a good thing, IMO. Implementation specific references are brittle when change occurs.
I think interfaces are the best thing in OO. You can decouple your application in modules, communicating trough well defined interfaces. This is the base for any mature system. Very easy to adapt.
But I take care to don't overuse, off course.
Interfaces to me is any abstract thing that link two worlds.
No they aren't.
One great use for interfaces are to hide the details of your implementation. If you use Eclipse and probably IntelliJ IDEA, you can navigate to an interface in your code and have the details of the implementation hidden.
And we do this with the J2EE api interfaces. We don't care about the details of session are or the request and response objects, we just want information about the method signatures.
An issue with favouring mocking (or any kind of runtime substition) through subclassing, rather than through an interface, is that you can only override the behaviour of virtual members.
Invoking a virtual member requires an additional level of indirection via a Vtable and is slower than a final member. Whereas using an interface adds a compile-time overhead, but using virtual members adds a runtime overhead to every member invocation.
Surely, adding an interface **just to support mocking** is far preferable to slowing down your entire app **just to suport mocking**?
My preference, therefore, is to favour 'final by default'.
Interfaces are just a great mechanism that allow proxying/call-interception...
Mocking is just one application of that technique. Lazy loading is another very interesting application.