martinfowler.com logo Home Blog Articles Books About Me Contact Me ThoughtWorks

TypedCollection design 17 June 2003 Reactions

When people are starting to work with objects, particularly in a strongly typed language, a common question is whether they should have specific collection classes for different domain types. So if you have a company class which stores a collection of employees, should you use a regular collection class from your libraries, or should you create a specific EmployeeList class - a typed collection.

(Of course if you have generics, then you would just use a parameterized class here - but I'll assume you are using something like Java or C# which don't yet have this feature.)

The main argument in favor of using a typed collection is that it promotes type-safety. You can ensure that only employees are added to the class, and you can also ensure that any elements you get from the collection are properly typed - thus avoiding a smelly downcast.

On the whole, however, it isn't worth the trouble. If you're using a collection you should be making it an EncapsulatedCollection, so that protects the type safety on updates. Handling the downcasting on access is a nice idea, but involves a lot of boilerplate code. You can reduce the pain of this with code generation - but my take is that it's more trouble than it's worth.


Links
home
bliki
feed 
Translations
Japanese
Spanish
Korean
Chinese
Thai
Categories
agile
design
dsl
leisure
refactoring
ruby
thoughtWorks
tools
uml
writing
Blog Roll
ThoughtBlogs
TW Alumni
Nicholas Carr
Steve Cook
Brian Foote
Simon Harris
Gregor Hohpe
/\ndy Hunt
Ralph Johnson
Patrick Logan
David Ing
Brian Marick
Jeremy Miller
Jimmy Nilsson
Samuel Pepys
Keith Ray
Johanna Rothman
Kathy Sierra
Dave Thomas

martinfowler.com logo mingle logo thoughtworks logo

© Copyright Martin Fowler, all rights reserved