Jam*_*hon 3 language-agnostic oop interface
返回对象时,我希望在实现层次结构中备份多远?
以Java集合接口为例,这是否合适?
Collection outerMethod() {
return innerMethod();
}
List innerMethod() {
List list = new ArrayList();
//do something with the list that requires a method in the List interface
return list;
}
Run Code Online (Sandbox Code Playgroud)
或者你想使用List作为外部方法的返回?
另一个例子,
List outerMethod() {
List list = innerMethod();
//do something with the list that requires a method in the List interface
return list;
}
Collection innerMethod() {
return new ArrayList();
}
Run Code Online (Sandbox Code Playgroud)
参数示例,
void outerMethod() {
innerMethod((List) innerMethodTwo);
}
void innerMethodOne(List list) {
//do something with the list
}
Collection innerMethodTwo() {
return new ArrayList();
}
Run Code Online (Sandbox Code Playgroud)
有人可以提供任何一般建议吗?
您的退货类型应尽可能具体,以便为您的方法的消费者提供最大的灵活性.同样,最佳做法是将任何参数的类型设置为尽可能抽象,以便您的方法的使用者在可以传递的类型方面具有更大的灵活性.
我发现在从类中公开类型时具体的问题的答案取决于您对调用者与您的类进行交互的期望和限制以及您的代码可能如何演变.这是一个复杂的平衡行为.
例如,如果您希望调用者需要按索引访问元素,则可以返回List
,但如果没有,则Collection
可能就足够了.如果您希望限制调用者只能迭代结果而不更改它们 - 您希望返回一个Iterable<>
包装器.如果您知道您的内部表示可能会发生变化,您可能希望避免返回像List这样的特定类,以便消费者可以更加脱离您的实现.
回答这些问题并不容易 - 没有正确或错误的答案 - 也没有完美的指导方针.它需要经验,思想和直觉.而且(像我们大多数人一样),你可能会弄错.
我会说,就个人而言,我错误地认为我从代码中暴露出更多限制 - 特别是当它不成熟而且还没有被广泛使用时.有时您可以返回并更改公共界面中的返回类型...有时您不能.