Sunday, March 13, 2011

API Design for collections

In this short but important lesson, you'll learn a few simple guidelines that will allow your API to interoperate seamlessly with all other fine APIs that follow these guidelines. In essence, these rules define what it takes to be a good citizen in the brave new world of collections.

In-Parameters

If your API contains a method that requires a collection on input, it is of paramount importance that you declare the relevant parameter type to be one of the collection interface types. Never use an implementation type, as this defeats the purpose of an interface-based collection framework, which is to allow collections to be manipulated without regard to implementation details. Further, you should always use the least specific type that makes sense. For example, don't require a List or a Set if a Collection would do. It's not that you should never require a List or a Set on input; it is correct to do so if a method depends on some property of one of these interfaces. For example, many of the algorithms provided by the Java platform require a List on input because they depend on the fact that lists are ordered. As a general rule, however, the best types to use on input are the most general: Collection and Map.


Caution: Never, never, define your own ad hoc collection class and require objects of this class on input. By doing this, you'd lose all the benefits provided by the collection framework.

No comments:

Post a Comment

Chitika