davidahines
davidahines

Reputation: 4094

Should I declare the interface as the return value or the implementation as the return value?

Which of the following is correct when writing a method that returns an arrayList of cats.

public List getCatsByCatHerderID(int id);

public ArrayList<Cat> getCatsByCatHerderID(int id);

public List<Cat> getCatsByCatHerderID(int id);

Upvotes: 0

Views: 63

Answers (3)

iluxa
iluxa

Reputation: 6969

The third one.

The first is bad since it'll force the user of your API to cast List entries, and he may choose to cast them to (Dog) for all you now.

The second is bad cause what if Java comes up with SuperFastList in 1.7, and you want to use that instead of ArrayList?

Upvotes: 2

Buhake Sindi
Buhake Sindi

Reputation: 89199

public List<Cat> getCatsByCatHerderID(int id);

The 3rd method, as you only deal with methods defined in list and never to worry of what type of list is returned by the method. Also, if you are going to use Web Services, the 3rd method is ok, as List is better understood in Web Services than ArrayList (imagine .NET having ArrayList?)

If you really want to return ArrayList, then this:

public ArrayList<Cat> getCatsByCatHerderID(int id);

Upvotes: 1

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

List<Cat> is the best choice. Firstly, it declares an interface as a return value, so you can modify the implementation later, for example switch from an ArrayList to something else. Secondly, it uses generics, which is always better, as it makes the value typesafe.

Upvotes: 4

Related Questions