[Newbies] enumerated types

Norbert Hartl norbert at hartl.name
Mon Oct 6 06:16:52 UTC 2008


On Sun, 2008-10-05 at 20:19 -0500, Mark Volkmann wrote:
> Have I summarized this correctly?
> Smalltalk doesn't support the concept of enumerated types like in Java
> 5 and above. Instead, the Smalltalk way is to:
> 
>      1. create a class that represents the enumerated type
>      2. add a class variable for each enumerated value (must start
>         uppercase)

I wouldn't create class variables for the enumerated stuff. You can
create a dictionary that holds the instances. It is more flexible
to. 

cache
   ^ cache ifNil: [ cache := Dictionary new ]

red
   ^ self cache at: #red ifAbsentPut: [ 
      self new
         ...
         ....
   ]

blue
   ^ self cache at: #blue ifAbsentPut: [ 
      self new
         ...
         ....
   ]
       
>      1. add a class-side initialize method that creates an instance of
>         the class for each enumerated value using basicNew and assigns
>         it the corresponding class variable
see above

>      1. prevent creation of additional instances by overiding the
>         class method new with "self error: 'new instances cannot be
>         created'"
see above

>      1. add class-side getter method for each enumerated value that
>         simply returns it
see above

I can see you have singletons in mind :) This approach is good if you
need constant objects that should provide a richer protocol than just
identity. 

Norbert

> Here's an example ColorEnum class.
> 
> Object subclass: #ColorEnum
>   instanceVariableNames: ''
>   classVariableNames: 'Blue Green Red'
>   poolDictionaries: ''
>   category: 'SomeCategory'
> 
> 
> initialize
>   Red := self basicNew.
>   Green := self basicNew.
>   Blue := self basicNew
> 
> 
> new
>   self error: 'new instances cannot be created'
> 
> 
> red
>   ^Red
> 
> 
> green
>   ^Green
> 
> 
> blue
>   ^Blue
> 
> ---
> Mark Volkmann
> 
> 
> 
> 
> 
> 
> 
> _______________________________________________
> Beginners mailing list
> Beginners at lists.squeakfoundation.org
> http://lists.squeakfoundation.org/mailman/listinfo/beginners



More information about the Beginners mailing list