06/10/2008

Class side variables, an alternative to Global variables

I have built my small experiment, using Globals, and it actually works quite well. However, over the weekend, I was thinking about whether I should use a Class instead of the Globals. Mark Volkmann was thinking similar thoughts, but with a different objective. He added this to the beginners' list


create a class that represents the enumerated type
add a class variable for each enumerated value (must start uppercase)
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
prevent creation of additional instances by overiding the class method
new with "self error: 'new instances cannot be created'"
add class-side getter method for each enumerated value that simply
returns it
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

No comments: