tags:

views:

450

answers:

12

I've been programming in Java for a few courses in the University and I have the following question:

Is it methodologically accepted that every class should implement an interface? Is it considered bad practice not to do so? Can you describe a situation where it's not a good idea to use interfaces?

Edit: Personally, I like the notion of using Interfaces for everything as a methodology and habit, even if it's not clearly beneficial. Eclipse automatically created a class file with all the methods, so it doesn't waste any time anyway.

+3  A: 

Following the YAGNI principle a class should implement an interface if you really need it. Otherwise what do you gain from it?

Edit: Interfaces provide a sort of abstraction. They are particularly useful if you want to interchange between different implementations(many classes implementing the same interface). If it is just a single class, then there is no gain.

Petar Minchev
+1  A: 

Interfaces are the way to get an polymorphism. So if You have only one implementation, one class of particularly type, You don't need an interface.

Michał Mech
Interfaces provide abstraction, not encapsulation.
Petar Minchev
I was thinking about polymorphism. I don't why I said encapsulation. My bad. Misspelling.
Michał Mech
+2  A: 

No, it's not necessary for every class to implement an interface. Use interfaces only if they make your code cleaner and easier to write.

If your program has no current need for to have more than 1 implementation for a given class, then you don't need an interface. For example, in a simple chess program I wrote, I only need 1 type of Board object. A chess board is a chess board is a chess board. Making a Board interface and implementing that would have just required more code to write and maintain.

It's so easy to switch to an interface if you eventually need it.

Kaleb Brasee
if you create a alone programmer it's easy but not if your code is already used by multiple projects: then you'll be considered a bad designer because you'll break the client's code.
Well yeah -- there's some cases where interfaces make sense, and classes in distributed libraries are one of those cases. But the OP didn't ask about that specific case, he was asking about all classes.
Kaleb Brasee
A: 

When I design a new system from scratch I use a component oriented approach, each component (10 or more classes) provide an interface, this allows me (sometimes) to reuse them.

  • When designing a Tool (Or a simple system) I think this must not neccessarily be an exentensible framework I introduce interfaces when I need a second implementation as an option.

  • I saw some products which exposed nearly every funtionality by an interface, it took simply too much time to understand unnecessary complexity.

stacker
+2  A: 

You don't need to create an interface if you are not going to use it.

Typically you need an interface when:

  • Your program will provide several implementations for your component. For example, a default implementation which is part of your code, and a mock implementation which is used in a JUnit test. Some tools automate creating a mock implementation, like for instance EasyMock.
  • You want to use dependency injection for this class, with a framework such as Spring or the JBoss Micro-Container. In this case it is a good idea to specify the dependencies from one class with other classes using an interface.
Philippe Grenet
+1 for unit testing and mocking. I use interfaces on almost all my classes precisely for this reason.
Philippe Beaudoin
@Philippe Modern mocking framework can mock classes.
Pascal Thivent
excuse the foolish question, but what is mocking framework?
Grue
A framework that creates a mock object for use in testing, such as JMock, EasyMock, or Mockito. They let you test interaction with an object without actually testing that object itself -- the mock can be configured to do whatever your test needs (return a hardcoded result, throw an exception, etc.).
Kaleb Brasee
+1  A: 

A good way of learning what are considered good methodologies, especially when it comes to code structure design, is to look at freely available code. With Java, the obvious example is to take a look at the JDK system libraries.

You will find many examples of classes that do not implement any interfaces, or that are meant to be used directly, such as java.util.StringTokenizer.

Avi
I'd add the caveat that the Java language and programming practices may have evolved since the class was originally written and the code hasn't changed to break backward compatibility. For example, several system libraries still use `static final` int or String constants for things that would be better using enums, classes that take or return Objects requiring a cast that would be better using generics, and classes whose methods only take Vectors or Hashtables because the Collections API hadn't been written yet.
Nate
+2  A: 

I've found that it is beneficial to define the public methods of a class in a corresponding interface and when defining references to other classes strictly use an interface reference. This allows for easy inversion of control, and it also facilitates unit testing with mocking and stubbing. It also gives you the liberty of replacing the implementation with some other class that implements that interface, so if you are into TDD it may make things easier (or more contrived if you are a critic of TDD)

Otávio Décio
+1  A: 

If you use Service Provider Interface pattern in your application interfaces are harder to extend than abstract classes. If you add method to interface, all service providers must be rewritten. But if you add non-abstract method to the abstract class, none of the service providers must be rewritten.

Interfaces also make programming harder if only small part of the interface methods usually have meaningfull implementation.

Ha
These aren't problems with interfaces per se - they are simply bad hierarchy designs. You'd have the same problems if you used the same badly designed hierarchy by extending classes.
Nate
+2  A: 

Creating an interface for every class is unnecessary. Some commonly cited reasons include mocking (unneeded with modern mocking frameworks like Mockito) and for dependency injection (e.g. Spring, also unneeded in modern implementations).

Create an interface if you need one, especially to formally document public interfaces. There are a couple of nifty edge cases (e.g. marker interfaces).

For what it's worth, on a recent project we used interfaces for everything (both DI and mocking were cited as reasons) and it turned out to be a complete waste and added a lot of complexity - it was just as easy to add an interface when actually needed to mock something out in the rare cases it was needed. In the end, I'm sure someone will wind up going in and deleting all of the extraneous interfaces some weekend.

I do notice that C programmers first moving to Java tend to like lots of interfaces ("it's like headers"). The current version of Eclipse supports this, by allowing control-click navigation to generate a pop-up asking for interface or implementation.

Will
+1  A: 

Every class does implement an interface (i.e. contract) insofar as it provides a non-private API. Whether you should choose to represent the interface separately as a Java interface depends on whether the implementation is "a concept that varies".

If you are absolutely certain that there is only one reasonable implementation then there is no need for an interface. Otherwise an interface will allow you to change the implementation without changing client code.

Some people will shout "YAGNI", assuming that you have complete control over changing the code should you discover a new requirement later on. Other people will be justly afraid that they will need to change the unchangeable - a published API.

If you don't implement an interface (and use some kind of factory for object creation) then certain kinds of changes will force you to break the Open-Closed Principle. In some situations this is commercially acceptable, in others it isn't.

Can you describe a situation where it's not a good idea to use interfaces?

In some languages (e.g. C++, C#, but not Java) you can get a performance benefit if your class contains no virtual methods.

In small programs, or applications without published APIs, then you might see a small cost to maintaining separate interfaces.

If you see a significant increase in complexity due to separating interface and implementation then you are probably not using interfaces as contracts. Interfaces reduce complexity. From the consumer's perspective, components become commodities that fulfil the terms of a contract instead of entities that have sophisticated implementation details in their own right.

richj
A: 

Using Interface is about to make your application framework resilient to change. Since as I mentioned here (http://stackoverflow.com/questions/2658288/multiple-inheritance-debates-ii-according-to-stroustrup) multiple inheritance was cancelled in java and c# which I regret, one should always use Interface because you never know what the future will be.

Preparing for the future before you know what the future holds leads to unnecessarily complicated code.
Kaleb Brasee
+1  A: 

To answer the OP's question in a very blunt way: no, not all classes need to implement an interface. Like for all design questions, this boils down to one's best judgment. Here are a few rule of thumbs I normally follow:

  • Purely functional objects probably don't need to (e.g. Pattern, CharMatcher – even though the latter does implement Predicate, it is secondary to its core function)
  • Pure data holders probably don't need to (e.g. LogRecord, Locale)
  • If you can envision a different implementation of a given functionality (say, in-memory Cache vs. disk-based Cache), try to isolate the functionality into an interface. But don't go too far trying to predict the future either.
  • For testing purposes, it's very convenient when classes that do I/O or start threads are easily mockable, so that users don't pay a penalty when running their tests.
  • There's nothing worse than a interface that leaks its underlying implementation. Pay attention where you draw the line and make sure your interface's Javadoc is neutral in that way. If it's not, you probably don't need an interface.
  • Generally speaking, it is preferable for classes meant for public consumption outside your package/project to implement interfaces so that your users are less coupled to your implementation du jour.

Note that you can probably find counter-examples for each of the bullets in that list. Interfaces are very powerful, so they need to be used and created with care, especially if you're providing external APIs (watch this video to convince yourself). If you're too quick in putting an interface in front of everything, you'll probably end up leaking your single implementation, and you are only making things more complicated for the people following you. If you don't use them enough, you might end up with a codebase that is equally hard to maintain because everything is statically bound and very hard to change. The non-exhaustive list above is where I try to draw the line.

Julien Silland