26

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

Dan Rayson
  • 1,315
  • 1
  • 14
  • 37
Hubert
  • 2,273
  • 1
  • 19
  • 14
  • 6
    @Kane: I would say that's a second implementation. – Bill the Lizard Jun 05 '09 at 14:04
  • 3
    I wouldn't normally call a mock a second implementation - certainly not one built dynamically with Rhino.Mocks etc. A *stub* might be called an implementation, just about... I think it makes more sense to talk about "only one production implementation" personally. It would be interesting to know whether that's what Hubert means. – Jon Skeet Jun 05 '09 at 14:13
  • 2
    I meant only one implementation, not even mocked for testing. – Hubert Jun 05 '09 at 14:23
  • proxy based AOP? proxy based remoting? declarative security / transaction demarcation? – toolkit Jun 05 '09 at 14:53
  • 1
    The questions is really "Why use interfaces at all?" – rtn Jun 06 '09 at 13:53
  • Umm... any class that implements an interface (implements keyword in java, : symbol in C#) is an implementation, by definition. It might or might not be a _meaningful_ implementation, but how could you possibly deny its quality as an implementation if it implements an interface? – Tamas Czinege Jun 12 '09 at 15:53
  • Possibly duplicate of http://stackoverflow.com/q/8531292/1055241 check out the accepted answer to understand the concept of interfaces. – gprathour Jan 25 '12 at 08:19
  • Possible duplicate of [Java Interfaces Methodology: Should every class implement an interface?](https://stackoverflow.com/questions/2659366/java-interfaces-methodology-should-every-class-implement-an-interface) – jaco0646 Oct 09 '18 at 13:42

25 Answers25

33

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
  • 398,270
  • 210
  • 566
  • 880
  • 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 Jun 05 '09 at 14:09
  • 2
    @jjnguy Why not plan on *adding* something later then planning to *remove*? – Aardvark Jun 05 '09 at 14:13
  • 10
    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 Jun 05 '09 at 14:16
  • 6
    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. – Mike Tunnicliffe Jun 05 '09 at 16:26
  • 2
    "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 Aug 12 '09 at 07:12
23

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
  • 10,195
  • 1
  • 32
  • 41
  • 6
    Isn't that what public and private (and protected) are for? – Aardvark Jun 05 '09 at 14:17
  • 1
    Strictly speaking, only if you want to inherit functionality from a superclass. – MattK Jun 05 '09 at 14:33
  • 2
    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 Jun 05 '09 at 14:35
  • 22
    Personally think it hurts readability, especially in an IDE when you keep following object and you end up in ZE INTERFACE! – Karl Jun 05 '09 at 14:41
  • @Aardvark - no. I agree with what Scott said. – GreenieMeanie Jun 05 '09 at 15:10
  • 1
    @scott "alternate implementations, or adapters/decorators" -- wouldn't that mean you *would* have more then one class using the interface? – Aardvark Jun 05 '09 at 15:57
  • 1
    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 Jun 05 '09 at 18:03
  • 1
    @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 Oct 06 '10 at 02:28
10

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
  • 136,852
  • 53
  • 295
  • 323
  • 11
    This is especially useful when you're coding in a team and others would otherwise be waiting on you before they can compile. – Cogsy Jun 05 '09 at 14:06
  • 2
    Then you have the sort-of "scaffolding" in your code that was only relevant while building the app. – Aardvark Jun 05 '09 at 14:21
  • @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 Jun 05 '09 at 14:36
  • 2
    @jjnguy "an extra interface"? One per class can add up. – Aardvark Jun 05 '09 at 16:02
  • I still feel that extra files aren't a big problem. – jjnguy Jun 05 '09 at 16:14
  • 1
    -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 Jun 05 '09 at 17:14
  • Re worded the statement to better reflect what I meant. – jjnguy Jun 05 '09 at 17:36
  • 3
    -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 Jun 12 '09 at 15:33
  • 1
    @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 Jun 12 '09 at 15:52
9

Because they miss C++ header files?

David Thornley
  • 56,304
  • 9
  • 91
  • 158
  • 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 Jun 05 '09 at 16:14
  • 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 Jun 05 '09 at 17:42
  • 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 Jun 08 '09 at 14:04
4

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

Community
  • 1
  • 1
CodingWithSpike
  • 42,906
  • 18
  • 101
  • 138
4

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
  • 14,570
  • 14
  • 61
  • 79
  • 4
    However, 99% of the time there is at least two implementations of a "class, one real, one used in testing" is there heck! – Karl Jun 05 '09 at 14:45
3

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
  • 2,927
  • 8
  • 31
  • 39
3

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

Aardvark
  • 8,474
  • 7
  • 46
  • 64
3

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
  • 59,598
  • 102
  • 325
  • 594
2

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
  • 2,951
  • 2
  • 28
  • 50
2

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
  • 80,494
  • 45
  • 196
  • 228
1

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 C
  • 944
  • 1
  • 10
  • 22
1

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
  • 6,959
  • 7
  • 41
  • 57
1

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
  • 25,531
  • 3
  • 32
  • 40
1

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
  • 38,225
  • 23
  • 120
  • 194
  • Seems odd for a language to encourage/require the use of an interface in order to do something effectively unrelated like memory management. – MusiGenesis Oct 06 '10 at 02:32
0

Some people always create interface because they can be auto generated, so they are justifying working time creating interfaces, no matter if they are really used or not.

For example, sometimes developers are evaluated per line of code written, so it make sense to use interface.

magallanes
  • 6,583
  • 4
  • 54
  • 55
0

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
  • 5,769
  • 6
  • 30
  • 40
  • 2
    Then you would extract interface, once you need it. – Hubert Jun 05 '09 at 14:10
  • 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 Jun 05 '09 at 14:15
  • Then you're just rewriting it later. Why not do it right the first time and save yourself the time later? – samoz Jun 05 '09 at 14:16
  • 2
    You can do mocking without interfaces. That's what cglib is for. – mamboking Jun 05 '09 at 14:40
  • many people understand mocking as sub-classing, its just sad :( – IAdapter Jun 07 '09 at 16:35
0

The ability to expand later on in the future.

samoz
  • 56,849
  • 55
  • 141
  • 195
  • 2
    Could quite happy extend without an interface. – Karl Jun 05 '09 at 14:43
  • 5
    or add an interface later, when you find you need it. – Alex B Jun 05 '09 at 15:45
  • @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 Jun 05 '09 at 16:16
  • 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 Jun 05 '09 at 16:20
  • @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 Jun 05 '09 at 17:05
  • No that might be a bad example. But I think my point remains valid. Take a look at IEnumerable, would you really want that to be a class? – Skurmedel Jun 05 '09 at 19:19
  • Also I wasnt talking about reading data in a byte/text fashion, I was talking about a higher abstraction than that. – Skurmedel Jun 05 '09 at 19:20
0

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ș
  • 14,123
  • 2
  • 39
  • 62
0

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
  • 49,809
  • 17
  • 109
  • 135
  • "abstract dependency" automatically means "interface" to you? Are abstract base classes second-class citizens or something? That's discrimination. – dss539 Jun 05 '09 at 17:09
0

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
  • 6,119
  • 3
  • 29
  • 47
0

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,151
  • 2
  • 10
  • 24
0

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
  • 5,155
  • 22
  • 27
0

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
  • 2,988
  • 3
  • 32
  • 47
-2

because an interface is best suited to definitively indicate the type

Dexygen
  • 12,287
  • 13
  • 80
  • 147
  • Hard to believe this got downmodded. Probably by somebody who declares ArrayList(s) rather than List(s)? – Dexygen Jun 06 '09 at 11:09