0

I would like know opinions about the next sentence:

"In a object oriented static typed language you should declare variables and parameters as broad as possible and return types as narrow as possible"

In some extreme this afirmation could produce this code:

interface  anyInterface<T> {
    Collection<T> getCollection();
}
class anyClass implements anyInterface<Integer> {
    @Override
    public ArrayList<Integer> getCollection() {
        ...
    }
}

Thanks in advance for your opinions.

JoseLuis
  • 29
  • 2

2 Answers2

4

"In a object oriented static typed language you should declare variables and parameters as broad as possible and return types as narrow as possible"

Taken literally, that is advising I declare all variables and parameters as Object (or whatever the base class is for a given language). That's clearly nonsense. Also, it is saying that I should not use an interface for a return type when I can use a specific type. That's also clearly nonsense.

There's some sense behind the words, eg in the .NET world, it's better to eg use IEnumerable<T> instead of T[] or List<T> if the collection is simply enumerated via eg foreach. Generally it's better to use an abstraction type (eg interface) over a concrete type. But that applies for return types from private methods as much as for parameters. So it's still not very good advice.

Finally, the "object oriented" part is irrelevant. Haskell, the functional language poster boy, has no support for OO, but it still supports polymorphism and it's strongly typed. The same "favour an abstraction type over a concrete type" applies there too.

So in conclusion, it's taken some basic sound advice, distorted it and got the message all wrong. So it's not good advice at all.

David Arno
  • 39,599
  • 9
  • 94
  • 129
-1

This guideline produces code that is as reusable as possible, whilst preserving type safety as much as possible. The idea is that by using the most general type in the calling code or method parameters, that code or method can be applied to as many types as possible, in a strongly typed language.

By making the return types of your method as narrow (derived) as possible, you enable the user of that method to use all the functionality of the return type provided; a more general type (base class or interface) would restrict the subsequent usage.

This statement is not specific to object oriented programming. It is true for all strongly typed languages. It can also be extended to generic or higher kinded types, but your specific example doesn't declare any variables or parameters, so it is irrelevant.