Another Gotcha

| | Comments (2)

Riffing off yesterday's post about a gotcha with computed properties, I want to spell out another uncommon gotcha that sometimes bites the unwary.

When you make a static local variable, you have to remember that it means this value is shared across all instances of the class. So if you have multiple instances of the class all calling the same method, using the same static variable, it can be set in ways you may not expect.

Let's take a look at what I mean. Make a project, and drag a StaticText onto Window1. In the MouseDown event, put the following code:
[rbcode] static sAlreadyCalled as Boolean = false

if sAlreadyCalled then return false
sAlreadyCalled = true

StaticText1.Text = "I've been setup!"[/rbcode]
Then, in the App class, set DefaultWindow to none (in the properties list) and put the following code in the Open event:
[rbcode] dim w, w2 as Window

w = new Window1
w.Show

w2 = new Window1
w2.Left = w.Left + w.Width
w2.Top = w.Top
w2.Show[/rbcode]
When you run the project, you will see two windows that are side by side. When you click in the content area of one, you will set the StaticText change captions. But no amount of clicking in the other window will set the caption. That's because the static local is shared by both instances of the window class.

This may seem very simple to you when you look at it in such easy cases. But it can sneak up and bite you if you're not careful since we're all so used to thinking of locals and properties being on a per-instance basis.

Remember, if you want something to happen for just one instance of the class, make it a property of the class! If it's meant to be shared amongst all instances of the class, then a static variable (or shared property) is the proper construct to use.

2 Comments

I'm not sure if classify this as a "gotcha" like your last post. This behavior is defined by the use of the static keyword.

The same could be said of the last post. The behavior there is the typical locking mechanism behavior -- it's just easy to forget about it. The same is true (I think) of using static.

Neither are meant as gotchas in the sense that there's an underlying bug to watch out for. They're both gotchas that mean "when you use these, stop and think about the ramifications" -- failing to do so causes bugs in your code.

Leave a comment

Disclaimer

I'm currently an employee of REAL Software. My blog is mine. The opinions represented in this blog are mine as well and may not represent my employer's opinions. All original material is copyrighted and property of the author.

REALbasic® is a registered trademark of REAL Software, Inc. REAL SQL Server™ and Lingua™ are pending trademarks of REAL Software, Inc. All rights reserved.