This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why create ArrayList of type List?

 
Franz Fountain
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's quite common to see code like:
List<String> myList = new ArrayList<String>();

My question is why not just do:
ArrayList<String> myList = new ArrayList<String>();


I don't see the advantage of using polymorphism in this case. I guess ArrayList doesn't have any methods that are not in the interface List or this would really cramp your style. Is the advantage because now if you want to change your implementation and use a LinkedList instead of an ArrayList that you can easily do that in one line? I don't think that's a very good reason and I haven't found any other.
 
Andy Morris
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thinking about coupling might help you.

Perhaps your myList is an attribute of a class and it has getters or setters for it. If your declared type was ArrayList then you'd be forcing all users of your code to use that implementation type, when they shouldn't really have to. By specifying your dependency on the interface you vastly reduce the coupling.

This can also have large implications on testing - think if that type wasn't a List and it was some sort of connection instead, you could end up forcing all users of the code to depend on a specific type of Connection (e.g a JDBCConnection), whereas their test might want to test specific behaviour from the connection obj such as a FailingConnection that one doesn't depend on a database and two can help mock specific circumstances.

A test is just one type of user of your code, and therefore just one example of a benefit of this approach, but there could be all sorts of users of your code which could benefit from this also.

The point I'm trying to make is that by always programming to the interface it should make your code much more flexible.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic