[Newbies] Enumeration type implementation

Ben Coman btc at openInWorld.com
Wed Jan 4 11:21:11 UTC 2012

(Resending since it didn't show up on the list overnight)

What is the best way to implement "enumerations" in Smalltalk. For 
instance, for a UML definition of...
<<enumeration>> Currency
  <<enum>> USD   'US dollar'
  <<enum>> EUR   'Eueropean euro'
  <<enum>> AUD    'Australian dollar'

here is my guess, consisting of 2 instance side methods and 3 class side 
Object subclass: #EpcimCurrency
   instanceVariableNames: 'value'
   classVariableNames: ''
   poolDictionaries: ''
   category: 'IEC61970-Domain-Enumerations'

EpcimCurrency >> value: aCurrency
   ( (self class) validate: aCurrency) ifTrue:
       [ value := aCurrency

EpcimCurrency >> value

EpcimCurrency class
   instanceVariableNames: 'enums'

EpcimCurrency class >> validate: aString
   enums ifNil: [ self initialize ].
   ^ enums includesKey: aString.

EpcimCurrency class >>  enums   "for displaying in pulldown menus"
   enums ifNil: [ self initialize ].
   ^enums copy

EpcimCurrency class >> initalize
   (enums := Dictionary new)
               add: 'USD'-> 'US dollar' ;
               add: 'EUR'-> 'European euro' ;
               add: 'AUD'-> 'Australian dollar' ;
               add: 'CAD'-> 'Canadian dollar' ;
               add: 'CHF'-> 'Swiss francs' ;
               add: 'CNY'-> 'Chinese yuan renminbi' ;
               add: 'DKK'-> 'Danish crown' ;
               add: 'GBP'-> 'British pound' ;
               add: 'JPY'-> 'Japanese yen' ;
               add: 'NOK'-> 'Norwegian crown' ;
               add: 'RUR'-> 'Russian ruble' ;
               add: 'SEK'-> 'Swedish crown' ;
               add: 'INR'-> 'India rupees' ;
               add: 'other'-> 'Another type of currency' .
   " (EpcimCurrency new value: 'AUD' ) value inspect  "      ----> 'AUD'
   " (EpcimCurrency new value: 'XXX') value  inspect  "      ----> nil
   " EpcimCurrency initialize  "
   " EpcimCurrency enums inspect "   ---> aDictionary
The other way I thought might be like `Color blue`, but I'm not sure what is gained.

Your feedback would be appreciated.

More information about the Beginners mailing list