Return a Collection or a List, not a LinkedList

By Alvin J. Alexander, devdaily.com

As I started to mention in another blog post, your Java code will be more flexible when you learn to return more-general object references. As a specific example, a Java method that returns a LinkedList or ArrayList will be more flexible if it returns a more-general reference, such as a List, or better yet, a Collection. Here's an example of a method that returns a LinkedList:

// before: method returns a LinkedList reference
private LinkedList getList()
{
  LinkedList list = new LinkedList();
  list.add("Hello");
  list.add("world");
  return list;
}

That code is too-specific. At least 99% of the time other developers don't need to know that you're really creating a LinkedList. You're much better off returning just a plain old List, or better yet, a Collection, like this:

// after: method returns a Collection reference
private Collection getList()
{
  Collection list = new LinkedList();
  list.add("Hello");
  list.add("world");
  return list;
}

The reference you return should really depend on the functionality you want to support. Because a LinkedList implements a List, and a List has a Collection as an interface, you really need to know what methods those interfaces support to make this decision. But it's worth taking a moment to learn them, and to then keep your code more general.


devdaily logo