Java best practice - return a List, not a LinkedList

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. In most cases other developers only need to see your interface, not your implementation. Put another way, does it matter to anyone else if you used a LinkedList or an ArrayList? If it doesn't matter, then return a List, or perhaps even a Collection.

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 (again, interface versus implementation details).

 

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.