title: When should I return the Interface and when the concrete class?
body: <p>when programming in Java I practically always, just out of habit, write something like this:</p>
  
  <pre><code>public List&lt;String&gt; foo() {
      return new ArrayList&lt;String&gt;();
  }
  </code></pre>
  
  <p>Most of the time without even thinking about it. Now, the question is: should I <em>always</em> specify the interface as the return type? Or is it advisable to use the actual implementation of the interface, and if so, under what circumstances?</p>
  
  <p>It is obvious that using the interface has a lot of advantages (that's why it's there). In most cases it doesn't really matter what concrete implementation is used by a library function. But maybe there are cases where it does matter. For instance, if I know that I will primarily access the data in the list randomly, a <code>LinkedList</code> would be bad. But if my library function only returns the interface, I simply don't know. To be on the safe side I might even need to copy the list explicitly over to an <code>ArrayList</code>:</p>
  
  <pre><code>List bar = foo();
  List myList = bar instanceof LinkedList ? new ArrayList(bar) : bar;
  </code></pre>
  
  <p>but that just seems horrible and my coworkers would probably lynch me in the cafeteria. And rightfully so.</p>
  
  <p>What do you guys think? What are your guidelines, when do you tend towards the abstract solution, and when do you reveal details of your implementation for potential performance gains?</p>