For example, if I have a function like
public List<E> sort(ArrayList<E> list) {...}
My classmate told me that we should use List as a return type, because the return type should be as wide as possible. Its reason here is that we can change to return a LinkedList or other type later if we are currently returning an ArrayList. This increases flexibility.
But the parameter of the function that we get should be as narrow as possible. This is due to the fact that we may need to use some function that is implemented only by ArrayList in our sort function.
So my question is this: are there generally accepted guidelines / best practices that recommend that the formal parameters of a function be as narrow as possible? If not, what will be the main arguments against?
===============================================
Just clarify this.
public List<E> sort(ArrayList<E> list) {...}
This is just an example, List and ArrayList can be replaced with any other Super Class and Sub. Suppose that some functions exist only in a Sub-class.
public <E> SuperClass<E> sort(SubClass<E> object) {...}
source share