views:

1340

answers:

24
+15  Q: 

Useless interfaces

Why would you ever use interface it you are going to have only one implementation of it?

A: 

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.

Lewis
Then you would extract interface, once you need it.
Hubert
OK and if you were doing TDD, you'd need the interface straight away, so you'd know that you'd need more than one implementation. This wasn't a criticism of your question and hardly worthy of a -1 seeing as you ended up agreeing with me!?.
Lewis
Then you're just rewriting it later.Why not do it right the first time and save yourself the time later?
samoz
You can do mocking without interfaces. That's what cglib is for.
mamboking
many people understand mocking as sub-classing, its just sad :(
01
+9  A: 

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.

jjnguy
This is especially useful when you're coding in a team and others would otherwise be waiting on you before they can compile.
Cogsy
Woot, I couldn't agree more with that!
jjnguy
Then you have the sort-of "scaffolding" in your code that was only relevant while building the app.
Aardvark
@aardvark No, it is still relevant for documentation purposes. And, having an extra interface in your codebase can't be that much of a problem.
jjnguy
@jjnguy "an extra interface"? One per class can add up.
Aardvark
I still feel that extra files aren't a big problem.
jjnguy
-1 for "I feel it is more important to make your job of coding easier than keep the code base clean." I would hate to maintain something written with that philosophy. In addition, creating an interface does nothing to make it 'easier to code' for the person creating the class. If your class is so huge that you get lost when thinking what should be public vs private, you probably have more serious design problems.
dss539
Re worded the statement to better reflect what I meant.
jjnguy
-1 for this based on the question above (single implementation of an interface). If you want to put the scaffolding in place, just write all the method headers into your class prior to coding the implementation. Same effect, no code smell.
kdmurray
@Cogsy, if other members of the team are waiting on your before you can compile: just check in a shell with the public methods in place. Then start filling it in. Same effect, but no pointless interfaces are created.
MarkJ
+18  A: 

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.

MattK
Isn't that what public and private (and protected) are for?
Aardvark
Strictly speaking, only if you want to inherit functionality from a superclass.
MattK
public/private help you separate what you want to expose in a specific class; they don't help you provide alternate implementations, or adapters/decorators, etc
Scott Stanchfield
Personally think it hurts readability, especially in an IDE when you keep following object and you end up in ZE INTERFACE!
Karl
@Aardvark - no. I agree with what Scott said.
GreenieMeanie
@scott "alternate implementations, or adapters/decorators" -- wouldn't that mean you *would* have more then one class using the interface?
Aardvark
I agree with getting all confused when you try to follow an object and end up in some d*mn interface! Still trying to figure out a way to do this right.
Mez
@Mez: in *theory*, you would never need to follow code past an interface - the implementation underneath would have been thoroughly tested and proven reliable already, so the problem (if there were one) would be in your code leading up to the interface. In *reality* ... yeah, right.
MusiGenesis
+3  A: 

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:

  1. Future expansion / enhancements placeholder

  2. Easy to implement Inversion of Control / Dependency Injection

  3. 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).

rally25rs
interfaces aren't required for spring dependency injection
Alex B
or for mocking, nowadays you can even mock static, private and final methods.
01
+21  A: 

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...)

Bill the Lizard
I really like coding a class to fit an interface. If it turns out that the interface really isn't needed, then it can be removed. But, it feels like there is a good end-point/goal when you are implementing an interface.
jjnguy
+1 for developers with their crystal balls...
Aardvark
@jjnguy Why not plan on *adding* something later then planning to *remove*?
Aardvark
I agree that it can simplify things if you have the API defined separately from the implementation. The benefits are small when you only have one implementation, but they really add up when you have many (or even only two). It may be just an artifact of my coding practice (a very non-strict form of TDD), but I prefer to create one fully implemented class first, then tease the API out of it using refactoring.
Bill the Lizard
Chances are you'll get your inteface wrong anyway if you don't have more than one implementation in mind. I recall an argument that 3 alternate implementations of an interface is a good approximate number to ensure your interface is decently accurate.
fd
"Do not provide abstractions unless they are tested by developing several concrete implementations and APIs that consume the abstractions.If you ship abstractions without testing them in real-world scenarios, you will most likely miss design issues that are difficult or impossible to fix without introducing compatibility issues in future releases."http://msdn.microsoft.com/en-us/library/ms229019.aspx
Benjol
+2  A: 

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.

Karl
I agree. Start without it, if you need it later, refactor. http://c2.com/cgi/wiki?YouArentGonnaNeedIt
mamboking
does my nut? Is that a good or bad thing?
Aardvark
would only be good if i said nuts!
Karl
"Does my nut" Englishism for "Wrecks my head", "Head fcuk", "Twists my mellon", "Winds me up", "Makes my teeth grid" . . .
Binary Worrier
A: 

because an interface is best suited to definitively indicate the type

George Jempty
Hard to believe this got downmodded. Probably by somebody who declares ArrayList(s) rather than List(s)?
George Jempty
A: 

The ability to expand later on in the future.

samoz
Could quite happy extend without an interface.
Karl
or add an interface later, when you find you need it.
Alex B
@Karl: Let's say you have a class that takes other objects and uses them to read from, maybe a database or filesystem. The class itself doesn't care. This would be a good place to use an interface. In my eyes an interface specifies a requirement which the user has. For example: I need to get a user picture, I don't care where it comes from.
Skurmedel
What I mean in my above example is that the class might not care where the data comes from, it just knows what data it wants. If you specify the class to take some other class that reads from the database. What if you suddenly want to read from the filesystem, or maybe sometimes read from the db and sometimes from the filesystem? An interface let's you have two separate classes that do it differently, the client/user doesn't care.
Skurmedel
@Skurmedal - An abstract base class does the same thing. See System.IO.Stream in .NET. There is no need for an interface + abc + implementation in that situation.
dss539
No that might be a bad example. But I think my point remains valid. Take a look at IEnumerable<T>, would you really want that to be a class?
Skurmedel
Also I wasnt talking about reading data in a byte/text fashion, I was talking about a higher abstraction than that.
Skurmedel
+5  A: 

Because they miss C++ header files?

David Thornley
You know, maybe you're right? People talking about how interfaces makes things clearer and good for documentation might not think that way in C++ who's headers do that w/ or w/o interfaces!
Aardvark
That's an interesting idea...but C++ headers include a lot of implementation details that an interface declaration doesn't. So the argument for interfaces making things clearer isn't necessarily as strong for C++ headers.
Joseph
It would be nice, in some ways, if the C++ header didn't need implementation details. The interface information is what I find most helpful in the header files, and sometimes it's a bit annoying going through the implementation details.
David Thornley
A: 

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".

Cătălin Pitiș
+3  A: 

Some technologies require you use an interfaces. COM for one. Their you often have just one class implementing your interface.

Aardvark
I see the Java tag - so maybe this isn't quite on-topic...
Aardvark
A: 

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.

toolkit
"abstract dependency" automatically means "interface" to you? Are abstract base classes second-class citizens or something? That's discrimination.
dss539
+1  A: 

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.

Nicolas
+1  A: 

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.

Mark Lutton
+3  A: 

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?"

Kirschstein
However, 99% of the time there is at least two implementations of a "class, one real, one used in testing" is there heck!
Karl
Why, what's your excuse? :p
Kirschstein
Your problem with staying focused is quite... worrisome. It sounds almost as if you can't think abstractly without using an interface. Is this true?
dss539
+1 for the awesome stream of consciousness
Joel Mueller
+2  A: 

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.

G B
A: 

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?

quillbreaker
A: 

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.

Mike Hall
+1  A: 

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.

Kathy Van Stone
A: 

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.

Chochos
+1  A: 

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.

Juliet
+2  A: 

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.

AngryHacker
+1  A: 

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.

Jim McKeeth
Seems odd for a language to encourage/require the use of an interface in order to do something effectively unrelated like memory management.
MusiGenesis
A: 

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.

kdmurray