Java – Should the Most Specific Type Be Declared as Return Type?

inheritancejavaobject-orientedreturn-type

In Android I can put only ArrayList of Parcelable objects in Intent:

Intent putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value);

I can't put in there a List<? extends Parcelable>.

I have private method that get list of Parcelable objects from Intent (i.e. the method is used in its own class).

As I said there is always ArrayList in Intent. Should I declare return type of this method as ArrayList<>? Or List<>?

I think that ArrayList would be better because an ArrayList is also a List. But I often read that I should declare field type as most general possible type. I.e., Collection<> (or List<> if I need ordered collection) instead of ArrayList<>. But I don't see any reason to do so for this method return type.

Best Answer

A declaration (whether a return type, an API comment or a contract) is a promise that you will deliver some good or perform some service. Declaring a specific return type is a greater promise than declaring a general type that is good enough for the caller, because it ties you down do a more specific action.

If that is really what you are doing and always will be what you are doing, then there's no problem with that. But if one day you want to refactor, extend or improve your program in a way that involves a new, better container type, you won't be able to, because client code would break if you switch to CoolNewList structures. Then you will say to yourself, "Gee, I wish I had listened to those wise people at StackExchange and made minimal promises instead of boasting with concrete types!", but it will be too late for you. Then you will start advising younger coders to keep their promises minimal, and so the cycle of life continues.

Related Topic