views:

329

answers:

3

I don't mean a class variable. I want a variable that can be used everywhere. Where should I define it? [in squeak]

+2  A: 

One way is to make a singleton, as in this answer.

In general you make a class variable and accompanying class method to let some object become a globally accessible. See above mentioned singleton as an example. Such variable is then accesses from elsewhere:

global := MyClass myGlobalVar

To became also globally changeable, make mutator class method and call it like:

MyClass myGlobalVar: true

There are other ways too, but this one with class variables is portable around Smalltalk dialects, long term it is therefore the most safe way.

Janko Mivšek
OK, but I want the object to exist in every application. I thought about defining the variable as a class variable of the metaclass 'Object class'. That way this object could just be used, right? What do you think?
I'd certainly don't change such important classes like Object and other system ones just for that. If you'd use this variable in more that one application, make a common package with this class, which will hold this variable. Then load this package as a prerequisite of all other packages with your applications. This is nowadays considered most proper way for globals in Smalltalk.
Janko Mivšek
I think this is my answer. I have a few questins:1. Where to define the accessing method? In 'MyClass class'?2. How do I initialize the variable?
See the above mention singleton example. This can be extended to any such class variable.
Janko Mivšek
+6  A: 

Squeak stores all class instances and other global variables in the SystemDictionary called "Smalltalk". You can define a global variable like this:

Smalltalk at: #variableName put: theValue.

Refering to the variable variableName will return theValue.

However, good Smalltalk style is to avoid global variables altogether.

Nat
This is one posibility, but Smalltalkers are avoiding it, because it is very dangerous. If you by mistake name a variable the same as some existing class, you'll delete that class... That's why even in Squeak this approach is slowly depreciating. Other Smalltalks don't have it or have it differently.
Janko Mivšek
Smalltalkers prefer to avoid global variables altogether.
Nat
+1  A: 

Well a class in smalltalk is globally available und you can change it whenever you like. Just create a class and add your altering code as class methods. You can then access your stuff by calling

MyVariable thisOrThat
MyVariable updateThisOrThat: aThisOrThat
Norbert Hartl