Strange behavior / possible bug?

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Strange behavior / possible bug?

Leandro Perez-2
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
Reply | Threaded
Open this post in threaded view
|

Re: Strange behavior / possible bug?

Michael Lucas-Smith-2

>
> What would happen if we now send #bar to an instance of foo? would
> some kind of exception be raised?
The bar variable becomes a global undeclared variable. Removing the
instance variable recompiles all the methods on the class due to the
shape change. Unlike when you're creating the method it won't prompt you
about what to do with the missing variable - it'll just make them
undeclared.

The important thing to remember is that all instances of Foo will be
sharing the same bar variable :) .. This can be quite a tricky bug to
find at times when you're not expecting it.

Michael