Should You Always Code to Interfaces in Java

Should you always Code To Interfaces In Java

In general I agree with the other answers: use an interface when you know or anticipate change and/or different implementation, or go for testability.

But it's not always easy to know in advance what may change in the future, especially if you are not so experienced. I think the solution for that problem is refactoring: keep it simple (= no interface) as long as it is not needed. When the need arises simply do an "Introduce/Extract interface" refactoring (supported by almost all decent IDEs).

When you do it extract only those methods that are actually needed by the callers. Don't be afraid to extract more then one separate interfaces (if not all of the extracted methods are really coherent).

One driver of the refactoring might be the testing: if you can't easily test something with classes only consider introducing one/some interface(s). This will also allow you to use mocking which may greatly simplify testing in many cases.

Edit: based on Tarski's comment I've realized one more important scenario/adjustment to the previous statements:

If you provide an external API (for other [sub]projects, or really release it "to the wild") then using interfaces in the API (except for simple value classes) is almost always a good idea.

It will allow you to change the impl if you like without disturbing the client code. You will have a problem only if you also have to change the interface. Not breaking compatibility will be very tricky (if not impossible).

When should I use an interface in java?

Use interfaces to define an application programming contract (blueprint, interface) which "3rd-party" vendors have to fully adhere and implement. This way the endusers can just code against the API contract and easily switch of the concrete implementation "under the hoods" without changing the code.

The JDBC API is an excellent example. It exist of almost only interfaces. The concrete implementations are provided as "JDBC drivers". This enables you to write all the JDBC code independent of the database (DB) vendor. You can just change the JDBC driver without changing any line of Java code (except of any hardcoded DB-specific SQL code) whenever you'd like to switch of DB vendor.

Another example is the Java EE API, it also contains pretty much interfaces and abstract classes. The concrete implementations are provided as "Java EE application servers", "Servletcontainers", etc, such as Sun Glassfish, Apache Tomcat, etc. This enables you to deploy the webapplication (WAR) to whatever Java web server you like.

Does it always make sense to program to an interface in Java?

"Programming to an interface" does not mean "use the most abstracted version possible". In that case everyone would just use Object.

What it means is that you should define your program against the lowest possible abstraction without losing functionality. If you require a TreeMap then you will need to define a contract using a TreeMap.

Java Interfaces Methodology: Should every class implement an interface?

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.

When should I use an interface vs an implementation when declaring a new object?

It's ok to use both, but the former is preferred because it's always better to call an implementation's method using a reference to the Interface or super type (List). The former doesn't depend on the implementation and eliminates the need to change the code when the implementation (ArrayList) changes, but the latter requires you to change the code when the implementation changes to anything other than ArrayList.

What does program to interfaces, not implementations mean?

Interfaces are just contracts or signatures and they don't know
anything about implementations.

Coding against interface means, the client code always holds an Interface object which is supplied by a factory. Any instance returned by the factory would be of type Interface which any factory candidate class must have implemented. This way the client program is not worried about implementation and the interface signature determines what all operations can be done. This can be used to change the behavior of a program at run-time. It also helps you to write far better programs from the maintenance point of view.

Here's a basic example for you.

public enum Language
{
English, German, Spanish
}

public class SpeakerFactory
{
public static ISpeaker CreateSpeaker(Language language)
{
switch (language)
{
case Language.English:
return new EnglishSpeaker();
case Language.German:
return new GermanSpeaker();
case Language.Spanish:
return new SpanishSpeaker();
default:
throw new ApplicationException("No speaker can speak such language");
}
}
}

[STAThread]
static void Main()
{
//This is your client code.
ISpeaker speaker = SpeakerFactory.CreateSpeaker(Language.English);
speaker.Speak();
Console.ReadLine();
}

public interface ISpeaker
{
void Speak();
}

public class EnglishSpeaker : ISpeaker
{
public EnglishSpeaker() { }

#region ISpeaker Members

public void Speak()
{
Console.WriteLine("I speak English.");
}

#endregion
}

public class GermanSpeaker : ISpeaker
{
public GermanSpeaker() { }

#region ISpeaker Members

public void Speak()
{
Console.WriteLine("I speak German.");
}

#endregion
}

public class SpanishSpeaker : ISpeaker
{
public SpanishSpeaker() { }

#region ISpeaker Members

public void Speak()
{
Console.WriteLine("I speak Spanish.");
}

#endregion
}

alt text

This is just a basic example and
actual explanation of the principle is
beyond the scope of this answer.

EDIT

I have updated the example above and added an abstract Speaker base class. In this update, I added a feature to all Speakers to "SayHello". All speaker speak "Hello World". So that's a common feature with similar function. Refer to the class diagram and you'll find that Speaker abstract class implement ISpeaker interface and marks the Speak() as abstract which means that the each Speaker implementation is responsible for implementing the Speak() method since it varies from Speaker to Speaker. But all speaker say "Hello" unanimously. So in the abstract Speaker class we define a method that says "Hello World" and each Speaker implementation will derive the SayHello() method.

Consider a case where SpanishSpeaker cannot Say Hello so in that case you can override the SayHello() method for Spanish Speaker and raise proper exception.

Please note that, we have
not made any changes to Interface
ISpeaker. And the client code and
SpeakerFactory also remain unaffected
unchanged. And this is what we achieve by Programming-to-Interface.

And we could achieve this behavior by simply adding a base abstract class Speaker and some minor modification in Each implementation thus leaving the original program unchanged. This is a desired feature of any application and it makes your application easily maintainable.

public enum Language
{
English, German, Spanish
}

public class SpeakerFactory
{
public static ISpeaker CreateSpeaker(Language language)
{
switch (language)
{
case Language.English:
return new EnglishSpeaker();
case Language.German:
return new GermanSpeaker();
case Language.Spanish:
return new SpanishSpeaker();
default:
throw new ApplicationException("No speaker can speak such language");
}
}
}

class Program
{
[STAThread]
static void Main()
{
//This is your client code.
ISpeaker speaker = SpeakerFactory.CreateSpeaker(Language.English);
speaker.Speak();
Console.ReadLine();
}
}

public interface ISpeaker
{
void Speak();
}

public abstract class Speaker : ISpeaker
{

#region ISpeaker Members

public abstract void Speak();

public virtual void SayHello()
{
Console.WriteLine("Hello world.");
}

#endregion
}

public class EnglishSpeaker : Speaker
{
public EnglishSpeaker() { }

#region ISpeaker Members

public override void Speak()
{
this.SayHello();
Console.WriteLine("I speak English.");
}

#endregion
}

public class GermanSpeaker : Speaker
{
public GermanSpeaker() { }

#region ISpeaker Members

public override void Speak()
{
Console.WriteLine("I speak German.");
this.SayHello();
}

#endregion
}

public class SpanishSpeaker : Speaker
{
public SpanishSpeaker() { }

#region ISpeaker Members

public override void Speak()
{
Console.WriteLine("I speak Spanish.");
}

public override void SayHello()
{
throw new ApplicationException("I cannot say Hello World.");
}

#endregion
}

alt text

When to use Single method Interfaces in Java

With Java 8, keeping the single method interface is quite useful, since single method interfaces will allow the usage of closures and "function pointers". So, whenever your code is written against a single method interface, the client code may hand in a closure or a method (which must have a compatible signature to the method declared in the single method interface) instead of having to create an anonymous class. In contrast, if you make one interface with more than one method, the client code will not have that possibility. It must always use a class that implements all methods of the interface.

So as a common guideline, one can say: If a class that only exposes a single method to the client code might be useful to some client, then using a single method interface for that method is a good idea. A counter example to this is the Iterator interface: Here, it would not be useful having only a next() method without a hasNext() method. Since having a class that only implements one of these methods is no use, splitting this interface is not a good idea here.

Example:

interface SingleMethod{ //The single method interface
void foo(int i);
}

class X implements SingleMethod { //A class implementing it (and probably other ones)
void foo(int i){...}
}

class Y { //An unrelated class that has methods with matching signature
void bar(int i){...}
static void bar2(int i){...}
}

class Framework{ // A framework that uses the interface
//Takes a single method object and does something with it
//(probably invoking the method)
void consume(SingleMethod m){...}
}

class Client{ //Client code that uses the framework
Framework f = ...;
X x = new X();
Y y = new Y();
f.consume(x); //Fine, also in Java 7

//Java 8
//ALL these calls are only possible since SingleMethod has only ONE method!
f.consume(y::bar); //Simply hand in a method. Object y is bound implicitly
f.consume(Y::bar2); //Static methods are fine, too
f.consume(i -> { System.out.println(i); }) //lambda expression. Super concise.

// the above could even be more concise
// presenting all the beauty of the recent Java changes
f.consume(System.out::println)

//This is the only way if the interface has MORE THAN ONE method:
//Calling Y.bar2 Without that closure stuff (super verbose)
f.consume(new SingleMethod(){
@Override void foo(int i){ Y.bar2(i); }
});
}

What does it mean to program to an interface?

There are some wonderful answers on here to this questions that get into all sorts of great detail about interfaces and loosely coupling code, inversion of control and so on. There are some fairly heady discussions, so I'd like to take the opportunity to break things down a bit for understanding why an interface is useful.

When I first started getting exposed to interfaces, I too was confused about their relevance. I didn't understand why you needed them. If we're using a language like Java or C#, we already have inheritance and I viewed interfaces as a weaker form of inheritance and thought, "why bother?" In a sense I was right, you can think of interfaces as sort of a weak form of inheritance, but beyond that I finally understood their use as a language construct by thinking of them as a means of classifying common traits or behaviors that were exhibited by potentially many non-related classes of objects.

For example -- say you have a SIM game and have the following classes:

class HouseFly inherits Insect {
void FlyAroundYourHead(){}
void LandOnThings(){}
}

class Telemarketer inherits Person {
void CallDuringDinner(){}
void ContinueTalkingWhenYouSayNo(){}
}

Clearly, these two objects have nothing in common in terms of direct inheritance. But, you could say they are both annoying.

Let's say our game needs to have some sort of random thing that annoys the game player when they eat dinner. This could be a HouseFly or a Telemarketer or both -- but how do you allow for both with a single function? And how do you ask each different type of object to "do their annoying thing" in the same way?

The key to realize is that both a Telemarketer and HouseFly share a common loosely interpreted behavior even though they are nothing alike in terms of modeling them. So, let's make an interface that both can implement:

interface IPest {
void BeAnnoying();
}

class HouseFly inherits Insect implements IPest {
void FlyAroundYourHead(){}
void LandOnThings(){}

void BeAnnoying() {
FlyAroundYourHead();
LandOnThings();
}
}

class Telemarketer inherits Person implements IPest {
void CallDuringDinner(){}
void ContinueTalkingWhenYouSayNo(){}

void BeAnnoying() {
CallDuringDinner();
ContinueTalkingWhenYouSayNo();
}
}

We now have two classes that can each be annoying in their own way. And they do not need to derive from the same base class and share common inherent characteristics -- they simply need to satisfy the contract of IPest -- that contract is simple. You just have to BeAnnoying. In this regard, we can model the following:

class DiningRoom {

DiningRoom(Person[] diningPeople, IPest[] pests) { ... }

void ServeDinner() {
when diningPeople are eating,

foreach pest in pests
pest.BeAnnoying();
}
}

Here we have a dining room that accepts a number of diners and a number of pests -- note the use of the interface. This means that in our little world, a member of the pests array could actually be a Telemarketer object or a HouseFly object.

The ServeDinner method is called when dinner is served and our people in the dining room are supposed to eat. In our little game, that's when our pests do their work -- each pest is instructed to be annoying by way of the IPest interface. In this way, we can easily have both Telemarketers and HouseFlys be annoying in each of their own ways -- we care only that we have something in the DiningRoom object that is a pest, we don't really care what it is and they could have nothing in common with other.

This very contrived pseudo-code example (that dragged on a lot longer than I anticipated) is simply meant to illustrate the kind of thing that finally turned the light on for me in terms of when we might use an interface. I apologize in advance for the silliness of the example, but hope that it helps in your understanding. And, to be sure, the other posted answers you've received here really cover the gamut of the use of interfaces today in design patterns and development methodologies.

Should methods in a Java interface be declared with or without a public access modifier?

The JLS makes this clear:

It is permitted, but discouraged as a matter of style, to redundantly specify the public and/or abstract modifier for a method declared in an interface.

When should one use interfaces?

In languages such as Java and C# interfaces provide a means for a class to be have in a polymorphic manner. That is to say a class can satisfy more than one contract - it can behave as multiple different types, a class of one type can be substituted for another. In other languages this can also be provided by multiple inheritance, but there are various disadvantages to this approach. However, having a class behave as more than one type is not the most common motivation for using interfaces.

By programming to interfaces instead of classes you can also decouple your program from specific implementations. This makes it much easier to substitute one class implementation for another. This is particularly useful when writing unit tests where you may wish to swap some heavyweight class implementation with a lightweight mock object. If your program only expects an interface type, and both the heavyweight object and mock object implement said interface, then they are very easy to substitute.

Also, consider a simple Java example where I say have a program that displays pages of data on the screen. Initially I want it to get the data from a database or XML files. If I write my program so that it uses interfaces I can define an interface like so:

public interface PageDatasource {
public List<Page> getPages();
}

And use it like so:

PageDatasource datasource = // insert concrete PageDatasource implementation here
List<Pages> pages = datasource.getPages();
display(pages);

I can then write separate database and XML implementations that adhere to this interface:

public class DatabasePageDatasource implements PageDatasource {
public List<Page> getPages() {
// Database specific code
}
}

public class XmlPageDatasource implements PageDatasource {
public List<Page> getPages() {
// XML specific code
}
}

Because I used an interface I can now use either implementation - Database or XML - interchangeably without having to change the parts of my program that ask for the page data. The XML and Database implementations likely do completely different things but all my program cares about is that the object supplying the page data implements the PageDatasource interface.



Related Topics



Leave a reply



Submit