/result

Page 118

I SSUES

A third metaphor useful for thinking about collections is that of mathematical sets. A collection is a sack of objects just like a mathematical set is a sack of elements. A set divides the world into things in the set and things not in the set. A collection divides the world of objects into objects that are in the collection and objects that are not. Two basic operations on mathematical sets are finding their cardinality (the size() method of collections) and testing for inclusion (represented by the contains() method). The mathematical metaphor is only approximate for collections. The other basic operations on sets—union, intersection, difference, and symmetric difference—are not directly represented by collections. Whether this is because these operations are intrinsically less useful or because they aren’t used because they aren’t available makes for an interesting debate.

Issues Collections are used to express several orthogonal concepts in programs. In principle, you should express yourself as precisely as possible. With collections, this means using the most general possible interface as a declaration and the most specific implementation class. However, this is not an absolute rule. I carefully went through JUnit and generalized all the variable declarations. The result was a mess, because there was no uniformity. The confusion of having the same object declared as an Iterable in one spot, a Collection in another, and a List elsewhere made reading the code more difficult without much payoff. It was clearer to just declare every variable as a List. The first concept expressed by collections is their size. Arrays (which are primitive collections) have a fixed size, set when the array is created. Most collections can change size after they are created. A second concept expressed through collections is whether or not the order of elements is important. Calculations in which the elements affect each other or where external users of the calculation attach importance to order call for collections that preserve order. The order may be the order in which elements were added or it may be provided by some outside influence like lexicographic comparison. Another issue to be expressed by collections is the uniqueness of elements. There are computations where the presence or absence of an element is sufficient, others where an element needs to be able to be present multiple times in a collection for the computation to be correct.

101


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.