Why would you ever use interface it you are going to have only one implementation of it?
because you might end up having two or more in the future
ADDITION After reading some of the comments: Object mocking: this would imply that you WOULD have more than one implementation of your interface, yoru mock IS another implementation.
It can be very good practice to set up an interface
as a spec to code your class
to.
If you determine the public methods/functionality that your interface
will have you can lock that in place. Then it becomes much easier to code a class
when you have a clear functionality in mind for it.
I feel it is more important to make writing good code easier than keep the code base clean.
To separate the API from the implementation, which is often a good programming practice. It will help with readability, if nothing else. It will also allow someone using your code in the future to provide an alternate implementation of the interface if they so desire.
It bothers me too when people make an Interface, an Abstract, and an actual implementation for every class, even if there will never be more than one, and the 3 files are all nearly empty.
However, big uses would be:
Future expansion / enhancements placeholder
Easy to implement Inversion of Control / Dependency Injection
Easy to implement mocks for unit testing.
*Edit:
I noticed you have Spring in your tags too. If using Spring, then #2 above is probably the biggie. Its easier to design classes that expect interfaces, and you can swap out actual implementations of the interface in the Spring configuration (Dependency Injection).
If I knew for a fact that there would only ever be one implementation I wouldn't create an interface. This falls under YAGNI, IMO.
(Of course, it's rare that I know anything about the future for a fact...)
agreed i see this all the time and it does my nut. If for the time being their is only one implementation and unlikely to be more then I would leave it up to the next developer to identify and implement the interface when they deem appropriate.
because an interface is best suited to definitively indicate the type
I prefer not to define an interface, unless I really need it. IMO, interface is one of the most abused design patterns. I think the case you are refering to is due to asking the question "What if ... will be needed in the future?". Since the developer is not a fortune teller yet... I would stick to interface "under-usage".
Some technologies require you use an interfaces. COM for one. Their you often have just one class implementing your interface.
To promote loose coupling, it is considered better design to rely on an abstract dependency than tying yourself to a concrete class.
One example of where this practice is especially useful is Spring's proxy-based remoting approach., where your single implementation resides in a different JVM.
In some cases, for visibility: you might want certain parts of the code to see the concrete class and have access to the setters, and some others to see only getters: give them access to the interface only.
This cannot always be achieved with public/protected/private.
When I work with someone else on a project, for instance if I do the front end (Web application for instance) and the other person does all the database work, we start by writing an API. The side that faces me is all about the problem domain: classes for User, Administrator, Employee, SKU or whatever. Then we can work independently; she implements all the interfaces and I write the code that uses them.
If there truely ever is one implementation and only ever going to be one implementation, don't code an interface. (YAGNI).
However, 99% of the time there is at least two implementations of a class, one real, one used in testing.
The ease of separating and mocking parts of a system during testing is more than worth the added effort of creating an interface for one class.
As a side note, and perhaps this is just because I lack some self control, coding against interfaces keeps me a lot more focused when I am working on a particular class. I find myself thinking more of "and this interface I am calling will return/do this" rather than "and this class I'm works like this, it calls x, transforms y, communicates with z, puts the coffee on, fluffs the pillows, integrates n with respect to y and then returns an instance of monkey... wait, what was I doing again?"
One reason could be decoupling: if your classes are used by another developer, you can give him the source code for the interfaces, and keep the implementation detail for yourself.
If the implementation changes, and the "contract" defined in the interface doesn't, you'll be happy: your interface still describes what the class does, and nobody has to know how it does it.
A number of the other answers mention "working with others", and this is certainly a concern. A project with 10 programmers is going to have to approach things differently than a project with one, and unfortunately, laying out a software architecture in such a way that multiple people can contribute to it is something people seem to always learn the hard way.
Can anyone suggest any good books or articles?
I often do this and for several reasons:
1) It allows you to specify which features of a class are actually being used outside the class. This tells you which features you always need to support as long as that interface remains unchanged. This allows you to have other public methods in that class for whatever reason (to support other interfaces or for other objects that have an instance of the object and refer to it by the actual class name as opposed to through the interface).
2) It also trims down the list provided through intellisense to only the features supported by the interface.
3) And as stated above, it's useful for unit testing and mocking frameworks.
If you are working with a system that allows refactoring, you should only add interfaces if either it is needed for the specification (say, an external API) or if you need multiple implementations. I consider test objects to be valid interpretations, so if you need an interface in order to get it under test, that is a fine use of interfaces.
Value objects should rarely become interfaces, service objects should frequently become interfaces.
One situation for an interface for only one implementation: RMI. You have an object on one application and will use it from another app via RMI; you need to have an interface. That way you don't even have to include the implementation class on the calling app, which might save the calling app from including a bunch of J2EE stuff or external libraries that the implementation might use.
Another reason: Today you only have one implementation, but tomorrow there may be something in the JDK or an external library that could lead to changing that implementation (maybe creating a new one). Your system could change and you need to add a new implementation while keeping the old one; some maintenance, etc.
Single-method interfaces are usually avoidable when you work in languages which allow you to pass around functions as first-order values. To name a few examples:
Single-method Interfaces to pass around snippets of implementation logic:
public interface IComparable<T>
{
int CompareTo(T first, T second);
}
public static class Array<T>
{
public void Sort(T[] input)
{
if (T is IComparable) { /* sorting implementation */ }
else { Throw new Exception("Doesn't implement IComparable"); }
}
}
Can be replaced with:
public static class Array<T>
{
public void Sort(T[] input, Func<T, T, int> compare)
{
/* sorting implementation */
}
}
I consider the functional style above more readable and reusable.
Single-method interfaces for dependency-injection / mocking:
public interface IFailureNotifier
{
void HandleFailure(Exception ex);
}
public class TransactionProcessor
{
public IFailureNotifier FailureNotifier { get; set; }
public TransactionProcessor(IFailureNotifier failureNotifier)
{
this.FailureNotifier = failureNotifier;
}
public void ProcessItems(object[] items)
{
try
{
for(object item in items) { /* do stuff */ }
}
catch(Exception ex)
{
FailureNotifier.HandleFailure(ex);
}
}
}
Can be re-written as:
public class TransactionProcessor
{
public Action<Exception> FailureNotifier { get; set; }
public TransactionProcessor(Action<Exception> failureNotifier)
{
this.FailureNotifier = failureNotifier;
}
public void ProcessItems(object[] items)
{
try
{
for(object item in items) { /* do stuff */ }
}
catch(Exception ex)
{
FailureNotifier(ex);
}
}
}
The advantage of this approach is simpler class library: I don't need a soup of tiny objects to implement IFailureNotifier's single method, I just pass the implementation directly instead.
That's not to say that single-method interfaces are bad, you still want to wrap up a function in an interface if the function depends on underlying mutable state. However I personally find that most of the benefits of single-method interfaces are already provided by first-class functions.
If you will only have one implementation, I wouldn't do it. The arguments put forth here that you might have multiple implementations don't really stand up to close examination. If you do end up with multiple implementations, it takes about 5 seconds to extract the interface using either built-in Visual Studio tools or Resharper.
So yes, YAGNI - don't complicate your life until you have to.
Yes, especially with Delphi.
If you have an interface reference to a object then you get reference counting automatically. So it is really common to have an interface with only one implementation when you want the object to be cleaned up automatically. Reference counting is better than garbage collecting since the object's destructor is called as soon as the last reference either goes out of scope or is no longer referencing it.
An example of where it may make sense to create an interface for a single class is (as others have mentioned) when we might expect it to be extended.
For example, if I've got a tracking tool that I'm building for my own personal use, that'll use SQL server. I'm creating an interface for the DB abstraction even though the DB methods are contained to a single class. The reason is that it will make the job of extending the application to use other DB platforms simpler.
I realize that similar types of abstractions already exist in the .NET framework, but I figured this was a pertinent example.