5.5. More Than One

You often work with more than one instance of an object. You can aggregate those instances using an array or a collection class. I like to distinguish between two types of aggregations. The first is termed a group, the second a collection. A group is a set of objects, typically coded using an array or a linked list. When I use the [] symbol in a class description, I am implying a group, not necessarily a particular implementation of a group.

A collection is a set of objects, typically implemented by a collection class or template (Vector, List, etc.). Operations on a collection can include performing an operation on the collection as a whole, such as calculating the average value of an attribute for all objects in the collection, or finding a particular object matching a key value.

If you find you are performing more operations on a group, other than just passing it to other methods or enumerating it, you might want to turn it into its own class. Creating a specific collection class, instead of using classwide (static) methods, separates the concerns of operations on all the objects in a collection, from those operations on a single object.[*]

[*] A reviewer noted that this is not true in languages such as Ruby and Groovy, which support closures. Closures let you apply arbitrary operations to generic collections without resorting to creating a specific collection class.

For example, suppose that Sam wanted to keep track of the rental history of each ...

Get Prefactoring now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.