Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to program to a interface?

Tags:

I keep hearing the statement on most programming related sites:

Program to an interface and not to an Implementation

However I don't understand the implications?
Examples would help.

EDIT: I have received a lot of good answers even so could you'll supplement it with some snippets of code for a better understanding of the subject. Thanks!

like image 401
Kevin Boyd Avatar asked Sep 11 '09 22:09

Kevin Boyd


1 Answers

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.

like image 102
weiji Avatar answered Oct 06 '22 03:10

weiji