Object-Oriented – Why Use First Class Collections?

genericsobject-oriented

As per rule number 4 of Object Calisthenics by Jeff Bay (RTF) in The ThoughtWorks Anthology, it is recommended that one should "Use first-class collections".

Rule 4: First class collections

Application of this rule is simple:
any class that contains a collection should contain no other member
variables. Each collection gets wrapped in its own class, so now
behaviors related to the collection have a home. You may find that
filters become a part of this new class. Also, your new class can
handle activities like joining two groups together or applying a rule
to each element of the group.

What I could understand from this was that we should use a separate class wrapping up the collection and with methods to add,delete modify data of that collection.

and We need this so that we are sure of what datatype goes into the collection and what comes out.

In case we use generic collection (in languages where it is applicable), do we need to follow this rule?

If I am missing an important significance, please clarify.

Best Answer

Type safety is a very minor reason to use first-class collections. From your link:

Rule 4: First class collections Application of this rule is simple: any class that contains a collection should contain no other member variables. Each collection gets wrapped in its own class, so now behaviors related to the collection have a home. You may find that filters become a part of this new class. Also, your new class can handle activities like joining two groups together or applying a rule to each element of the group.

The idea here is if you find yourself searching, filtering, validating, or anything beyond add/remove/iterate semantics on a collection, the code is asking you to put it in its own class. If you need to update just one value (after a search), that probably goes in the collection class.

The reasoning for this is pretty simple, collections tend to get passed around. Soon enough, 4 different classes have their own SearchByID() method. Or you get return values like Map<Integer, String> with the context of what's stored in that map stripped away. A first-class collection is a simple solution that costs a single source file. In practice, once those are in place (they're very easy to write unit tests for as well), any change dealing with the collection is easy to handle, like when SearchByID needs to take a GUID instead of an int.

Related Topic