简体   繁体   English

我应该将接口声明为返回值还是将实现声明为返回值?

[英]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. 在编写返回cats的arrayList的方法时,以下哪一项是正确的。

public List getCatsByCatHerderID(int id);

public ArrayList<Cat> getCatsByCatHerderID(int id);

public List<Cat> getCatsByCatHerderID(int id);

List<Cat> is the best choice. List<Cat>是最佳选择。 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. 首先,它声明一个接口作为返回值,因此您以后可以修改实现,例如从ArrayList切换到其他东西。 Secondly, it uses generics, which is always better, as it makes the value typesafe. 其次,它使用泛型,它总是更好,因为它使值类型安全。

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. 第一个不好,因为它会迫使您的API用户强制转换List条目,而他现在可能会选择将它们强制转换为(Dog)。

The second is bad cause what if Java comes up with SuperFastList in 1.7, and you want to use that instead of ArrayList? 第二个不好的原因是,如果Java在1.7中提供了SuperFastList,而您想使用它而不是ArrayList呢?

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. 第三种方法,因为您只处理list中定义的方法,而不必担心该方法返回哪种列表类型。 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 ?) 另外,如果您要使用Web服务,则第三种方法也可以,因为List在Web服务中比ArrayList更好理解(想象.NET具有ArrayList吗?)

If you really want to return ArrayList , then this: 如果您确实要返回ArrayList ,则此操作:

public ArrayList<Cat> getCatsByCatHerderID(int id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM