Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming to Interfaces, how generic is too generic? [closed]

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?

like image 760
James McMahon Avatar asked Apr 09 '26 09:04

James McMahon


1 Answers

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.

like image 72
Andrew Hare Avatar answered Apr 11 '26 03:04

Andrew Hare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!