Hello list, I've just bumped into something that looks kind of strange
We have a simple class called Foo that has no instance variables.
Now, we implement lazy initialization on a non existing instance variable...
i.e.
Foo >> bar
bar isNil ifTrue:[bar := 2].
^bar.
Of
course, when we try to save this method, a dialog appears letting us
know that 'bar' is not declared and asking us what to do.
Typically we would declare 'bar' as an instance variable and
everything would be just fine, but, what if we leave it undeclared?
I realize that leaving variables undeclared is not a common practice,
but what if the variable is deleted afterwards as a consequence of an
incorrect refactoring?
What would happen if we now send #bar to an instance of foo? would some kind of exception be raised?
Actually,
if we send #bar to an instance of Foo, 2 is returned...It looks strange
because we are returning the value of a non existing variable...
now, even more strange, if we modify this implementation, changing the initialization value to anything else like
i.e.
Foo >> bar
bar isNil ifTrue:[bar := 3].
^bar.
and send #bar again to an instance of foo, the old value 2 is returned instead of 3..
why does smalltalk behave this way? is this because the variable is cached? when does an undeclared variable get created?
I'm using VisualWorks NonCommercial, 7.5
Thanks a lot
Leandro