How far back up the implementation hierarchy do I want to go when returning an object?
Using the Java collection interface as an example, would this be appropriate?
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;
}
Or would you want to use List as a return for the outer method?
Another example,
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();
}
An example with parameters,
void outerMethod() {
innerMethod((List) innerMethodTwo);
}
void innerMethodOne(List list) {
//do something with the list
}
Collection innerMethodTwo() {
return new ArrayList();
}
Can anyone offer any general advice?
Your return type should be as specific as possible to give the consumer of your method the greatest flexibility. In the same spirit it is also best practice to make the types of any parameters as abstract as possible so that consumers of your method also have greater flexibility in what types they can pass in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With