September 16, 2004

Naked Collections are a Design Smell.

I've been thinking some time about a malaise that seems to afflict the codebase of most applications that I work with:

Collections.

Don't get me wrong, Collections are an important part of the programming toolkit, but every time I see them exposed in a method signature I wince. Collections are used as a convenvient shortcut instead of actually thinking in an object oriented way. The Collection is as far as many people go in modelling the bulk properties of groups of objects.

We model individual objects very carefully. If we are properly object-oriented we provide methods to the object that we are creating and end up with a beautifully crafted object. Yet when we come to model a group of objects, most often they seem to just get chucked into a Collection. The only bulk behaviours that we get are those of the Collection and none of those of the group.

Properly clothed collections.

When a collection class is wrapped in a 'group class' we create better object models. We can make our code more robust and easy to understand.
  • A wrapped collection can be strongly typed through the methods provided by the 'group class'.
  • When one comes to write bulk and batch methods they have a more natural home than the proliferation of helper classes that one normally has to sort through.
  • A group class can provide facets to the enclosed objects, for example when an instance of a 'Person' class is added to an instance of a 'Football Team' group class they become an instance of a 'Football Player' class. The addition of the 'Person' to the team should be accomplished through a method that has the necessary additional parameters for defining them as a football player, such as shirt number and position.

Using naked Collections is not object-oriented, when I see them used I know that someone has skimped on the modelling.

Groups of objects are objects too.


No comments: