326

Isn't the whole point of an interface that multiple classes adhere to a set of rules and implementations?

Luis Gouveia
  • 103
  • 5
Lamin Sanneh
  • 3,975
  • 3
  • 19
  • 19
  • 25
    see http://programmers.stackexchange.com/questions/150045/what-is-the-point-of-having-every-service-class-have-an-interface – k3b Aug 07 '12 at 07:53
  • 19
    Or to make it easier to unittest. –  Aug 07 '12 at 13:41
  • 11
    Allowing multiple classes to implement Interfaces and having your code depend on the interfaces is ESSENTIAL to isolation for unit testing. If you are doing unit testing, you will have another class implementing that interface. – StuperUser Aug 07 '12 at 14:10
  • The whole point of interfaces is to allow compile-time validation of method calls, preventing occurrences of 'Method not found' exceptions (as long as the run-time environment matches the compile-time environment). – kevin cline Aug 07 '12 at 16:49
  • This why I love dynamically bound languages - Unless you're checking `isinstance()`, all you care about is that whatever came in has the function/method/property you want to look at. Of course that makes good testing a priority... but requiring good practice isn't exactly a criticism... – Wayne Werner Aug 08 '12 at 11:12
  • 2
    [Reddit discussion](http://www.reddit.com/r/programming/comments/xtw8u/do_i_need_to_use_an_interface_when_only_one_class/) on this question. – yannis Aug 09 '12 at 01:03
  • 9
    Public fields and methods are an "interface" in their own right. If the lack of polymorphism is intentionally planned then there is no reason to use an interface. The unit testing others mentioned is a planned use of polymorphism. – mike30 Dec 13 '12 at 19:04
  • How about the only class implementing that interface does more than just implement that particular interface and you don't want the code needing only the methods of said interface to have access to the rest of the public methods of the class. For eaxmple classes that implement both "immutable" and "mutable" behavior and you want most of your code to have an extra "insulation" layer between them and the methods that change an instance's state (insulation provided by having to "ask" whether the "mutable" interface is supported) so it is easy to spot the code that messes with state. – Marjan Venema May 09 '15 at 18:27
  • Found a perfect use case for an interface implemented by a single class just now, in this thread: http://programmers.stackexchange.com/questions/281979/is-my-usage-of-explicit-casting-operator-reasonable-or-a-bad-hack – Marjan Venema May 09 '15 at 19:19

15 Answers15

244

Strictly speaking, no you don't, YAGNI applies. That said, the time you'll spend creating the interface is minimal, especially if you have a handy code generation tool doing most of the job for you. If you are uncertain on whether you are going to need the interface of or not, I'd say it's better to err on the side of towards supporting the definition of an interface.

Furthermore, using an interface even for a single class will provide you with another mock implementation for unit tests, one that's not on production. Avner Shahar-Kashtan's answer expands on this point.

yannis
  • 39,547
  • 40
  • 183
  • 216
  • 97
    +1 testing means you almost always have two implementations anyway – jk. Aug 07 '12 at 08:16
  • How does an interface apply to YAGNI? The linked wikipedia entry (to me) errs towards supporting the definition of an interface, rather than against it? – Deco Aug 07 '12 at 08:22
  • @Deco YAGNI == Don't build something you ain't going to need. If you are absolutely certain you don't have any use for the contract, why design by it? But of course, if you are _not_ certain, then it's better to err towards supporting the definition of an interface, all you will have wasted is a little bit of time. – yannis Aug 07 '12 at 08:26
  • 34
    @YannisRizos Disagree with your latter point because of Yagni. Cranking an interface from a classes public methods is trivial after the fact, as is replacing CFoo with IFoo in consuming classes. There's no point in writing it in advance of the need. – Dan Is Fiddling By Firelight Aug 07 '12 at 12:26
  • @DanNeely that's assuming you have Resharper. – MattDavey Aug 07 '12 at 13:23
  • 3
    @MattDavey Even without Resharper (or its equivalent in other languages) it should only take a minute or two even on large classes. Deleting out anything private and the bodies of public methods isn't a difficult process. – Dan Is Fiddling By Firelight Aug 07 '12 at 13:30
  • @DanNeely I've updated the answer. – yannis Aug 07 '12 at 15:38
  • 7
    I'm still not sure I'm following your reasoning. Since code generation tools make adding it after the fact even cheaper, I see even less of a reason to create the interface before you have an explicit need for it. – Dan Is Fiddling By Firelight Aug 07 '12 at 17:11
  • 2
    @dan Not every language has handy code generation tools and not every developer likes using code generation tools even if they are available to them. – yannis Aug 07 '12 at 17:13
  • 8
    I think a missing Interface is not a good example for YAGNI but for a "broken Window" and missing Documentation. The users of the class are practically forced to code against the implementation, instead of the abstraction as they should. – Fabio Fracassi Aug 08 '12 at 09:02
  • 1
    @YannisRizos, even if they don't, I think I'd agree with Fabio about the non-violation of YAGNI. My personal opinion about developing in a statically bound language is that if you create a class, it probably needs an interface. The *only* exception (I've seen) is if the behavior of the class is actually part of another, interface'd class' API (e.g. a UserControl on a View). Then the tests against the interface should expose errors in the other class. – Wayne Werner Aug 08 '12 at 11:17
  • 4
    This assumes that every class should be mock tested, which is something that I would seriously question. – Konrad Rudolph Aug 08 '12 at 15:13
  • @KonradRudolph I'd love to read your answer, if you have the time to write one. – yannis Aug 08 '12 at 16:41
  • @YannisRizos I agree pretty much with your answer, but primarily the YAGNI aspect since, as I said, mocking isn’t always required. – Konrad Rudolph Aug 08 '12 at 18:07
  • 18
    Why would you ever pollute your codebase with meaningless cruft just to satisfy some testing framework? I mean seriously, I'm just a self-taught JavaScript client-side guy trying to sort out WTF is wrong with C# and Java developer OOD implementations I keep encountering in my pursuit of becoming more of a well-rounded generalist but why don't they slap the IDE out of your hands and not let you have it back until you learn how to write clean, legible code when they catch you doing that sort of thing in college? That's just obscene. – Erik Reppen Feb 12 '13 at 00:20
  • 3
    `using an interface even for a single class will provide you with another mock implementation for unit tests, one that's not on production` but mockito allow to create mock for a concrete class. So you shouldn't count it as a second implementation- thus no need for an interface? – user23621 Oct 23 '14 at 09:15
  • +1 for @DanNeely to post an answer to this question. I strongly endorse his perspective on the subject. – Julian A. Jul 31 '15 at 22:30
  • @Fabio Fracassi Coding against an interface doesn't mean against the special class named interface in java or C#. It means: code against the most abstract type in the inheritance hierarchy. For example, don't specify a Button parameter if Control fit the needs. Coding against IMyClass and MyClass is the same. MyClass has an implicit interface, as any class does. – Sylvain Rodrigue Jun 01 '20 at 10:10
196

I would answer that whether you need an interface or not does not depend on how many classes will implement it. Interfaces are a tool for defining contracts between multiple subsystems of your application; so what really matters is how your application is divided into subsystems. There should be interfaces as the front-end to encapsulated subsystems, no matter how many classes implement them.

Here's one very useful rule of thumb:

  • If you make class Foo refer directly to class BarImpl, you're strongly committing yourself to change Foo every time you change BarImpl. You're basically treating them as one unit of code that's split across two classes.
  • If you make Foo refer to the interface Bar, you're committing yourself instead to avoid changes to Foo when you change BarImpl.

If you define interfaces at the key points of your application, you give careful thought to the methods that they should support and which they should not, and you comment the interfaces clearly to describe how an implementation is supposed to behave (and how not), your application will be a lot easier to understand because these commented interfaces will provide a sort of specification of the application—a description of how it's intended to behave. This makes it much easier to read the code (instead of asking "what the heck is this code supposed to do" you can ask "how does this code do what it's supposed to do").

In addition to all of this (or actually because of it), interfaces promote separate compilation. Since interfaces are trivial to compile and have fewer dependencies than their implementations, it means that if you write class Foo to use an interface Bar, you can usually recompile BarImpl without needing to recompile Foo. In large applications this can save a lot of time.

sacundim
  • 4,748
  • 1
  • 19
  • 16
  • 25
    I would upvote this much more than once, if I could. IMO the best answer to this question. – Fabio Fracassi Aug 08 '12 at 09:05
  • 7
    If the class is only performing one role (ie would only have one interface defined for it), then why not do this via public/private methods? – Matthew Finlay Aug 08 '12 at 23:50
  • 6
    1. Code organization; having the interface in its own file that has only signatures and documentation comments helps keep code clean. 2. Frameworks that force you to expose methods that you'd rather keep private (e.g., containers that inject dependencies through public setters). 3. Separate compilation, as mentioned already; if class `Foo` depends on interface `Bar` then `BarImpl` can be modified without having to recompile `Foo`. 4. Finer-grained access control than public/private offers (expose the same class to two clients through different interfaces). – sacundim Aug 09 '12 at 00:56
  • 3
    And last one: 5. Clients (ideally) shouldn't care how many classes my module has or how many, or even be able to tell. All they should see is a set of *types*, and some factories or façades to get the ball rolling. I.e., I often see value in encapsulating even what classes your library consists of. – sacundim Aug 09 '12 at 01:01
  • +1 for separate compilation, which is sadly missing from the other answers. If class A uses class B directly, depending on language, A may need recompiling every time B is recompiled. Depend on an interface instead, and it only needs to be recompiled when the interface changes. See Bob Martin's original article on the Interface Segregation Principle for a detailed example in C++ (which is probably the worst language for this problem, but it exists in others too). – Jules Aug 01 '15 at 08:43
  • related to what is already written, but it's also great for keeping dirty dependencies out of layers you don't want them in. in you domain entities project, you probably want to be able to reference some kind of abstract repository for said entities. however, that doesn't mean you want a repository implementation in that project, because it will probably reference some DB vendor or some ORM and stuff like that. those things have nothing to do with the domain logic, and so they belong in another project focused on persistance. – sara Jul 19 '16 at 14:07
  • *This makes it much easier to read the code (instead of asking "what the heck is this code supposed to do" you can ask "how does this code do what it's supposed to do").* Brilliant explanation – Alexander Derck Sep 08 '16 at 07:29
  • 17
    @sacundim `If you make class Foo refer directly to class BarImpl, you're strongly committing yourself to change Foo every time you change BarImpl` On changing BarImpl, what are the changes that can be avoided in Foo by using `interface Bar`? Since as long as signatures & functionality of a method doesn't change in BarImpl, Foo won't require change even without interface (the whole purpose of interface). I'm talking about the scenario where only one class i.e. `BarImpl` implements Bar. For multi class scenario, I understand Dependency Inversion Principle and how it interface is helpful. – Shishir Gupta Jun 18 '18 at 18:05
  • 3
    @ShishirGupta I was thinking the same. A good example there would be necessary to help to understand what he exactly means. – Anna Klein May 02 '19 at 19:48
  • 1
    @Shishir Gupta This is a common misunderstanding of interface. Many developpers doesn't know that every class has an implicite interface. Creating IMyClass and using it instead of MyClass add no isolation from (implicite) interface changes. – Sylvain Rodrigue Jun 01 '20 at 10:20
119

Interfaces are designated to define a behaviour, i.e. a set of prototypes of functions/methods. The types implementing the interface will implement that behavior, so when you deal with such a type you know (partly) what behavior it has.

There is no need to define an interface if you know that the behavior defined by it will be used only once. KISS (keep it simple, stupid)

yannis
  • 39,547
  • 40
  • 183
  • 216
superM
  • 7,363
  • 4
  • 29
  • 38
77

No, you don't need them, and I consider it an anti-pattern to automatically make interfaces for every class reference.

There is a real cost to making Foo/FooImpl for everything. The IDE may create the interface/implementation for free, but when you're navigating code, you have the extra cognitive load from F3/F12 on foo.doSomething() taking you to the interface signature and not the actual implementation you want. Plus you have the clutter of two files instead of one for everything.

So you should only do it when you actually need it for something.

Now addressing the counterarguments:

I need interfaces for Dependency injection frameworks

Interfaces to support frameworks are legacy. In Java, interfaces used to be a requirement for dynamic proxies, pre-CGLIB. Today, you usually don't need it. It's considered progress and a boon for developer productivity that you don't need them anymore in EJB3, Spring etc.

I need mocks for unit testing

If you write your own mocks and have two actual implementations, then an interface is appropriate. We probably wouldn't be having this discussion in the first place if your codebase had both a FooImpl and a TestFoo.

But if you're using a mocking framework like Moq, EasyMock, or Mockito, you can mock classes and you don't need interfaces. It's analogous to setting foo.method = mockImplementation in a dynamic language where methods can be assigned.

We need interfaces to follow Dependency Inversion Principle (DIP)

DIP says you build to depend on contracts (interfaces) and not implementations. But a class is already a contract and an abstraction. That's what the public/private keywords are for. In university, the canonical example was something like a Matrix or Polynomial class -- consumers have a public API to create matrixes, add them etc. but aren't allowed to care if the matrix is implemented in sparse or dense form. There was no IMatrix or MatrixImpl required to prove that point.

Also, DIP is often over-applied at every class/method call level, not only at major module boundaries. A sign that you're over-applying DIP is that your interface and implementation change in lock-step such that you have to touch two files to make a change instead of one. If DIP is applied appropriately, it means that your interface shouldn't have to change often. Also, another sign is that your interface only has one real consumer (its own application). Different story if you're building a class library for consumption in many different apps.

This is a corollary to Uncle Bob Martin's point about mocking -- you should only need to mock at major architectural boundaries. In a webapp the HTTP and DB access are the major boundaries. All the class/method calls in between are not. Same goes for DIP.

See also:

wrschneider
  • 1,259
  • 1
  • 10
  • 9
  • 10
    Mocking classes rather than interfaces (at least in Java and C#) should be considered deprecated, as there is no way to prevent the superclass constructor running, which may cause your mock object to interact with the environment in unintended ways. Mocking an interface is safer and easier because you don't have to think about constructor code. – Jules Aug 01 '15 at 08:53
  • 14
    I haven't run into problems with mocking classes, but I have been frustrated by IDE navigation not working as expected. Solving a real problem beats a hypothetical one. – wrschneider Aug 03 '15 at 11:32
  • 1
    @Jules You can mock a concrete class including its constructor in Java. – assylias Nov 19 '15 at 15:03
  • 1
    @assylias how do you prevent the constructor running? – Jules Nov 19 '15 at 17:54
  • 3
    @Jules It depends on your mocking framework - with jmockit for example, you can just write `new Mockup() {}` and the whole class, including its constructors, are mocked, whether it's an interface, abstract class or concrete class. You can also "override" the constructor behaviour if you wish to do so. I suppose there are equivalent ways in Mockito or Powermock. – assylias Nov 19 '15 at 18:22
  • @assylias I prefer to use hard-coded doubles rather than mock frameworks because (a) I think the test code is often clearer using them, (b) they are easier to refactor with automated refactoring tools, and (c) they run faster, which is pretty important for large test suites. I'm not the only one who prefers not to use heavy-weight frameworks, either (e.g. [Uncle Bob](https://blog.8thlight.com/uncle-bob/2014/05/14/TheLittleMocker.html) also doesn't use mock frameworks much). You can't do this plain Java. – Jules Nov 20 '15 at 12:17
  • Moq can only mock concrete classes IF the members are virtual. I have no interest in adding virtual to every member of every class. Following up on Jules' comment, since constructors cannot be declared as virtual, then Moq would have no way to intercept the constructor call. For navigation, I solve the problem by keeping both in the same file, the interface within a #region. I'm searching and reading to find better alternatives but still haven't found any better approach that stands. – Etienne Charland Feb 19 '19 at 14:31
  • I believe first bullet point to link is: https://www.adam-bien.com/roller/abien/entry/service_s_new_serviceimpl_why – Prakash Mar 30 '21 at 00:34
68

While in theory you shouldn't have an interface just for having-an-interface's sake, Yannis Rizos's answer hints at further complications:

When you're writing unit tests and using mock frameworks such as Moq or FakeItEasy (to name the two most recent ones I've used), you're implicitly creating another class that implements the interface. Searching the code or static analysis might claim that there's just one implementation, but in fact there's the internal mock implementation. Whenever you start writing mocks, you'll find that extracting interfaces makes sense.

But wait, there's more. There are more scenarios where there are implicit interface implementations. Using .NET's WCF communication stack, for instance, generates a proxy to a remote service, which, again, implements the interface.

In a clean code environment, I agree with the rest of the answers here. However, pay attention to any frameworks, patterns or dependencies you have that might make use of interfaces.

Avner Shahar-Kashtan
  • 9,166
  • 3
  • 29
  • 37
  • 2
    +1: I'm not sure YAGNI applies here, as having an interface and using frameworks (e.g. JMock, etc) that utilise interfaces can actually save you time. – Deco Aug 07 '12 at 08:21
  • 7
    @Deco: good mocking frameworks (JMock among them) don't even need interfaces. – Michael Borgwardt Aug 07 '12 at 22:45
  • 22
    Creating an interface solely because of a limitation of your mocking framework seems like an awful reason to me. Using, for example, EasyMock mocking a class is as easy as an interface anyway. – Alb Aug 08 '12 at 13:41
  • 8
    I would say it's the other way around. Using mock objects in testing means creating alternative implementations to your interfaces, by definition. This is true whether you create your own FakeImplementation classes or let mocking frameworks do the heavy lifting for you. There may be some frameworks, like EasyMock, that use various hacks and low-level tricks to mock concrete classes - and more power to them! - but conceptually, mock objects are alternative implementations to a contract. – Avner Shahar-Kashtan Aug 08 '12 at 13:47
  • 2
    You're not firing off the tests in production. Why does a mock for a class that didn't need an interface, need an interface? – Erik Reppen Feb 12 '13 at 00:39
  • 1
    This is a good point. We frown at inserting debugging- or testing-specific code into production code, so why do we architect our code for testing? I think this is mostly a matter of trade-offs. Adding an interface isn't a very big deal, it has very little performance or correctness implications, if any, and using modern tools, you aren't even wasting time writing the interface code. Assuming unit testing is a meaningful part of your dev cycle, it's a sacrifice of "cleanliness" for the sake of practicality. – Avner Shahar-Kashtan Feb 12 '13 at 05:44
  • `using an interface even for a single class will provide you with another mock implementation for unit tests, one that's not on production` but mockito allow to create mock for a concrete class. So you shouldn't count it as a second implementation- thus no need for an interface? – user23621 Oct 23 '14 at 09:16
  • @user23621 see my answer to Alb above. – Avner Shahar-Kashtan Oct 23 '14 at 12:12
  • 1
    @AvnerShahar-Kashtan conceptually I agree. I ask practically is it worthy to manage interface when the mocking FW create implicit one any way. Interfaces make it harder to navigate in code. Adds more files to the project structure and should be re-factored when the concrete changes its signatures. – user23621 Oct 23 '14 at 21:18
26

It looks like the answers on both sides of the fence can be summed up in this:

Design well, and put interfaces where interfaces are needed.

As I noted in my response to Yanni's answer, I don't think you can ever have a hard and fast rule about interfaces. The rule needs to be, by definition, flexible. My rule on interfaces is that an interface should be used anywhere you're creating an API. And an API should be created anywhere you're crossing the boundary from one domain of responsibility into another.

For (a horribly contrived) example, let's say you're building a Car class. In your class, you'll certainly need a UI layer. In this particular example, it takes the form of an IginitionSwitch, SteeringWheel, GearShift, GasPedal, and BrakePedal. Since this car contains an AutomaticTransmission, you don't need a ClutchPedal. (And since this is a terrible car, there is no A/C, radio, or seat. As a matter of fact, the floorboards are missing too - you just have to hang on to that steering wheel and hope for the best!)

So which of these classes need an interface? The answer could be all of them, or none of them - depending on your design.

You could have an interface that looked like this:

Interface ICabin
    Event IgnitionSwitchTurnedOn()
    Event IgnitionSwitchTurnedOff()
    Event BrakePedalPositionChanged(int percent)
    Event GasPedalPositionChanged(int percent)
    Event GearShiftGearChanged(int gearNum)
    Event SteeringWheelTurned(float degree)
End Interface

At that point, the behavior of those classes becomes part of the ICabin Interface/API. In this example the classes (if there are some) are probably simple, with a few properties, and a function or two. And what you are implicitly stating with your design is that these classes exist solely to support whatever concrete implementation of ICabin you have, and they cannot exist on their own, or they are meaningless outside of the ICabin context.

It's the same reason that you don't unit-test private members - they exist only to support the public API, and thus their behavior should be tested by testing the API.

So if your class exists solely to support another class, and conceptually you view it as not really having it's own domain then it's fine to skip the interface. But if your class is important enough that you consider it grown up enough to have it's own domain, then go ahead and give it an interface.


EDIT:

Frequently (including in this answer) you'll read things like 'domain', 'dependency' (frequently coupled with 'injection') that don't mean a thing to you when you're beginning to program (they sure didn't mean anything to me). For domain, it means exactly what it sounds like:

The territory over which dominion or authority is exerted; the possessions of a sovereign or commonwealth, or the like. Also used figuratively. [WordNet sense 2] [1913 Webster]

In the terms of my example - let's consider the IgnitionSwitch. In a meatspace car, the ignition switch is responsible for:

  1. Authenticating(not identifying) the user (they need the correct key)
  2. Providing current to the starter so it can actually start the car
  3. Providing current to the ignition system so it can continue to operate
  4. Shutting off current so the car will stop.
  5. Depending on how you view it, in most (all?) newer cars there's a switch that prevents the key from being removed from the ignition while the transmission is out of Park, so this could be part of its domain. (Actually it means I need to rethink and redesign my system...)

Those properties make up the domain of the IgnitionSwitch, or in other words, what it knows about and is responsible for.

The IgnitionSwitch is not responsible for the GasPedal. The ignition switch is completely ignorant of the gas pedal in every way. They both operate completely independent of one another (though a car would be fairly worthless without both of them!).

As I originally stated, it depends on your design. You could design an IgnitionSwitch that had two values: On (True) and Off (False). Or you could design it to authenticate the key provided for it, and a host of other actions. That's the hard part of being a developer is deciding where to draw the lines in the sand - and honestly most of the time it's completely relative. Those lines in the sand are important though - that's where your API is, and thus where your interfaces should be.

Wayne Werner
  • 2,340
  • 2
  • 23
  • 23
12

No (YAGNI), unless you are planning to write tests for other classes using this interface, and those tests would benefit from mocking the interface.

stijn
  • 4,108
  • 1
  • 25
  • 31
8

From MSDN:

Interfaces are better suited to situations in which your applications require many possibly unrelated object types to provide certain functionality.

Interfaces are more flexible than base classes because you can define a single implementation that can implement multiple interfaces.

Interfaces are better in situations in which you do not need to inherit implementation from a base class.

Interfaces are useful in cases where you cannot use class inheritance. For example, structures cannot inherit from classes, but they can implement interfaces.

Generally in the case of a single class, it will not be necessary to implement an interface, but considering the future of your project, it could be useful to formally define necessary behavior of classes.

lwm
  • 895
  • 1
  • 5
  • 12
6

Since you asked this question, I suppose that you have already seen the interests of having an interface hiding multiple implementations. This can be manifested by the dependency inversion principle.

However, the necessity to have an interface or not doesn't depend on the number of its implementations. The real role of an interface is that it defines a contract stating what service should be provided instead of how it should be implemented.

Once the contract defined, two or more teams can work independently. Say you are working on a module A and it depends the module B, the fact to create an interface on B allows to continue your work without worrying about B's implementation because all details are hidden by the interface. Thus, distributed programming becomes possible.

Even though module B has only one implementation of its interface, the interface is still necessary.

In conclusion, an interface hides implementation details from its users. Programming to interface helps to write more documents because contract must be defined, to write more modular software, to promote unit tests and to accelerate development speed.

Hui Wang
  • 161
  • 1
  • 3
  • 3
    Every class can have a public interface (the public methods) and a private interface (the implementation details). I could argue that the public interface of class is the contract. You don't need an extra element to work to that contract. – Fuhrmanator Mar 21 '14 at 17:25
6

All answer here are very good. Indeed most of the time you don't need to implement a different interface. But there are case where you may want to do it anyway. Here is some case where I do it :

The class implement another interface that I don't want to expose
Happen often with adapter class that bridge third party code.

interface NameChangeListener { // Implemented by a lot of people
    void nameChanged(String name); 
} 

interface NameChangeCount { // Only implemented by my class
    int getCount();
}

class NameChangeCounter implements NameChangeListener, NameChangeCount {
    ...
}

class SomeUserInterface {
    private NameChangeCount currentCount; // Will never know that you can change the counter
}

The class use a specific technology that shouldn't leak trough
Mostly when interacting with external libraries. Even if there is only one implementation I use an interface to ensure that I don't introduce unnecessary coupling with the external library.

interface SomeRepository { // Guarantee that the external library details won't leak trough
    ...
}

class OracleSomeRepository implements SomeRepository { 
    ... // Oracle prefix allow us to quickly know what is going on in this class
}

Cross layer communication
Even if only one UI class ever implements one of the domain class, it allow for better seperation between those layer and most importantly it avoid cyclic dependency.

package project.domain;

interface UserRequestSource {
    public UserRequest getLastRequest();
}

class UserBehaviorAnalyser {
    private UserRequestSource requestSource;
}

package project.ui;

class OrderCompleteDialog extends SomeUIClass implements project.domain.UserRequestSource {
    // UI concern, no need for my domain object to know about this method.
    public void displayLabelInErrorMode(); 

    // They most certainly need to know about *that* though
    public UserRequest getLastRequest();
}

Only a subset of the method should be available to most object
Mostly happen when I have some configuration method on the concrete class

interface Sender {
    void sendMessage(Message message)
}

class PacketSender implements Sender {
    void sendMessage(Message message);
    void setPacketSize(int sizeInByte);
}

class Throttler { // This class need to have full access to the object
    private PacketSender sender;

    public useLowNetworkUsageMode() {
        sender.setPacketSize(LOW_PACKET_SIZE);
        sender.sendMessage(new NotifyLowNetworkUsageMessage());

        ... // Other details
    }
}

class MailOrder { // Not this one though
    private Sender sender;
}

So in the end I use interface for the same reason that I use private field : other object shouldn't have access to stuff they shouldn't access. If I have a case like that, I introduce an interface even if only one class implement it.

Laurent Bourgault-Roy
  • 5,606
  • 4
  • 20
  • 25
5

To answer the question: There is more to it than that.

One important aspect of an interface is the intent.

An interface is "an abstract type that contains no data, but exposes behaviors" - Interface (computing) So if this is a behavior, or a set of behaviors, that the class supports, than an interface is likely the correct pattern. If, however, the behavior(s) is(are) intrinsic to the concept embodied by the class, then you likely do not want an interface at all.

The first question to ask is what is the nature of the thing or process that you are trying to represent. Then follow on with the practical reasons for implementing that nature in a given way.

Joshua Drake
  • 350
  • 4
  • 10
4

Interfaces are really important but try to control the number of them that you have.

Having gone down the road of creating interfaces for just about everything it is easy to end up with 'chopped-up spaghetti' code. I defer to the greater wisdom of Ayende Rahien who has posted some very wise words on the subject:

http://ayende.com/blog/153889/limit-your-abstractions-analyzing-a-ddd-application

This is his first post of a whole series so keep reading!

Lord Spa
  • 51
  • 1
4

One reason you still might want to introduce an interface in this case is to follow the Dependency Inversion Principle. That is, the module which uses the class will depend on an abstraction of it (i.e. the interface) instead of depending on a concrete implementation. It decouples high-level components from the low-level components.

dodgy_coder
  • 1,098
  • 7
  • 22
2

There is no real reason to do anything. Interfaces are to help you and not the output program. So even if the Interface is implemented by a million classes there is no rule that says you have to create one. You create one so that when you, or anyone else who uses your code, wants to change something it percolates to all implementations. Creating an interface will aide you in all future cases where you might want to create another class that implements it.

John Demetriou
  • 672
  • 1
  • 10
  • 18
2

There is not always a need to define an interface for a class.

Simple objects like value objects don't have multiple implementations. They don't need to be mocked either. The implementation can be tested on its own and when other classes are tested that depend on them, the actual value object can be used.

Remember that creating an interface has a cost. It needs to be updated along the implementation, it needs an extra file, and some IDE will have trouble zooming in the implementation, not the interface.

So I would define interfaces only for higher level classes, where you want an abstraction from the implementation.

Note that with a class you get an interface for free. Besides the implementation, a class defines an interface from the set of public methods. That interface is implemented by all derived classes. It is not strictly speaking an interface, but it can be used exactly in the same way. So I don't think it is necessary to recreate an interface that already exists under the name of the class.

Florian F
  • 1,127
  • 1
  • 6
  • 13