views:

38

answers:

3

I believe that it's better to code to interfaces instead of implementations. In Java:

List<User> users = new ArrayList<User>();

There's no need to specify the runtime type of users all over the program if the code only cares that it implements List.

However, I encounter many people who believe that it's totally fine, even when they're not using properties specific to the ArrayList:

ArrayList<User> users = new ArrayList<User>();

I try to explain that it's redundancy and makes the program harder to change, but they don't seem to care. Are there other reasons that this is important? Or perhaps my convictions are overstated?

+2  A: 

Personally, I think that there are two parts to this argument.

  1. If you're returning an object from a method in a class, it should return the most generic object possible. In this case, if you had a choice between returning ArrayList<User> or List<User>, return List<User> because it makes life easier for the people consuming your class.

  2. If you're coding inside of a method and you don't mind hard-coding a concrete type, go for it. It's not what I would do, and it will make your code more fragile in the future but since there are no outside dependencies on that concrete type (hence the first part), you're not going to break anybody that is consuming your code.

Justin Niessner
nice guidelines, and describes where you can relax the rules and tradeoffs.
hvgotcodes
+2  A: 

Testability is one reason. If you implement using implementations it is very difficult to mock out the required object and use it in tests. You usually end up extending the implementation and overriding which is painful.

stimms
i forgot about testability in my answer. facepalm
hvgotcodes
A: 

It is extremely important if you want to use dependency injection. It is also important for hibernate -- you MUST specify an interface if you have a collection type, because hibernate provides its own collection implementations.

That said, you don't need to be pedantic about it -- sometimes it doesn't matter. Sometimes you want to specify concrete type to get at methods only available on that type.

hvgotcodes

related questions