What does it mean to program to an interface?

You are probably looking for something like this:

public static void main(String... args) {
  // do this - declare the variable to be of type Set, which is an interface
  Set buddies = new HashSet();

  // don't do this - you declare the variable to have a fixed type
  HashSet buddies2 = new HashSet();
}

Why is it considered good to do it the first way? Let’s say later on you decide you need to use a different data structure, say a LinkedHashSet, in order to take advantage of the LinkedHashSet’s functionality. The code has to be changed like so:

public static void main(String... args) {
  // do this - declare the variable to be of type Set, which is an interface
  Set buddies = new LinkedHashSet();  // <- change the constructor call

  // don't do this - you declare the variable to have a fixed type
  // this you have to change both the variable type and the constructor call
  // HashSet buddies2 = new HashSet();  // old version
  LinkedHashSet buddies2 = new LinkedHashSet();
 }

This doesn’t seem so bad, right? But what if you wrote getters the same way?

public HashSet getBuddies() {
  return buddies;
}

This would have to be changed, too!

public LinkedHashSet getBuddies() {
  return buddies;
}

Hopefully you see, even with a small program like this you have far-reaching implications on what you declare the type of the variable to be. With objects going back and forth so much it definitely helps make the program easier to code and maintain if you just rely on a variable being declared as an interface, not as a specific implementation of that interface (in this case, declare it to be a Set, not a LinkedHashSet or whatever). It can be just this:

public Set getBuddies() {
  return buddies;
}

There’s another benefit too, in that (well at least for me) the difference helps me design a program better. But hopefully my examples give you some idea… hope it helps.

Leave a Comment