Generics

Phil Hudson phil.hudson at iname.com
Sun Sep 28 08:43:41 UTC 2003



>On Sun, Sep 28, 2003 at 01:05:13AM +0100, Phil Hudson wrote:
>> Are generic/template/parameterized/typesafe collections available in
>> Smalltalk? 

<snip>

>Can you give examples of where the standard
>collection classes do not meet your needs?

Sure. First off, I'm happy to accept Brian's definition of type in
Smalltalk as fine-grained interfaces; that is, object A is the same type
as object B if it responds to the same message.

A Collection can hold zero or more elements, each of any type. Sometimes
you nevertheless need to ensure that all elements are of the same type.
Say you're collecting Integers and by accident you insert a Symbol
representing an integer value, say #'3'. Your code assumes that every
element of your collection will respond to #even; therefor, it errors
when it iterates over the Symbol element. You can choose to trap this
*particular* error in this *particular* case, or you can (should be able
to) choose to use a Collection that takes care of ensuring this *general
case* of error *cannot* occur.

Indeed, I would argue that, to a first approximation, type consistency in
a Collection is what you *always* need. Therefore, you always need to be
able to *automatically* detect erroneous elements.

C++ provides templates, which solve the problem at the language level.
The general approach to ensuring Collection element type consistency in
languages that don't have templates is to parameterize each Collection
object C with a class (or interface) P against which element type
membership can be tested.

The problem is exactly the same in Java: Collection elements can be any
object. What I do in Java is take the Decorator design pattern approach.
I use type-safe wrappers for each subclass of Collection. Instances I
create of Set, SortedSet, etc. are each wrapped with TypeSafeSet,
TypeSafeSortedSet, etc. The wrappers validate each Collection element for
a type I specify when the wrapper is created. And, usefully, once you are
sure that all your Collections are type-safe, you can globally switch all
the wrapper-adder methods to become identity functions, so that the call
to wrap a Collection simply returns the unmodified, non-type-safe
Collection. Thus you lose the checking overhead (and the wrapper object
creation overhead) once you have validated the consistency of all your
Collection elements.

BTW, "generics" is a (badly named, IMO) synonym of the other terms. It's
the term usually used in discussions of adding type-safe collections to
Java. It doesn't mean what you (and I, initially) intuitively grasped. I
don't know how it originated.



More information about the Squeak-dev mailing list