[Newbies] Enumeration "type" implementation

Ben Coman btc at openInWorld.com
Tue Jan 3 18:35:32 UTC 2012


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 
methods...
-------------------------
Object subclass: #EpcimCurrency
    instanceVariableNames: 'value'
    classVariableNames: ''
    poolDictionaries: ''
    category: 'IEC61970-Domain-Enumerations'

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

EpcimCurrency >> value
    ^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

Any suggestions


More information about the Beginners mailing list