Use generic collection interfaces as parameters

Functions that take collection parameters should take the generic parameter. E.g. don’t do this:

public void process(ArrayList list);

do this instead:

public void process(List list);

This avoids putting unnecessary requirements on the parameter. In particular, you can do these:

thing.processList(Collections.EMPTY_LIST);
thing.processList(Collections.singletonList(item));
LinkedList linkedList = getLinkedList();
thing.processList(linkedList);

instead of having to do these:

thing.processList(new ArrayList());
ArrayList list = new ArrayList(1);
list.add(item);
thing.processList(list);
LinkedList linkedList = getLinkedList();
thing.processList(new ArrayList(linkedList));
Share This | Comments | Permalink | Trackback | Comments feed

One response

  • Of course. This don’t just apply to collections but potentially to any class. This is the rule #1 of OO Design Patterns.

    Diego | 14 February 2008

Post a comment

(required)
(required)
Close
E-mail It