About STATIC in Xojo

Statics serve a useful purpose
But, you do have to be aware of how they behave.

Suppose you create a STATIC in a method on a class.
Be aware that this will exist ONCE for ALL instance of the class (this may or may not be desirable for your purposes)

As a quick example if you do

Class Class1
     Computed Property Foo as String
          Get as string
              static msg as String
              if msg = "" then
                 msg = "this gets called once"  
              end if
          end get
     End Property
End Class

and then in other code do

Dim c1 As New class1

Dim u1 As String = c1. Foo

Dim c2 As New Class1

Dim u2 As String = c2. Foo


note how many time the break statement is reached in the Getter regardless of how many instances you create

with STATIC there is ONE instance across ALL instances - much like a shared property behaves

so heads up !



Thanks - I just discovered a major bug in my app that I didn’t even suspect was there.

Yeah static can be kind of surprising in this way
There are a few gotchas I’ve come across over the years like this :slight_smile:

Nice illustration @npalardy. Like @MarkusWinter, I need to now fix some broken code…

STATIC can also cause weird multi-threading bugs.
For example, if multiple threads called a function that read / write a static value they could end up treading on each other’s toes. Granted, this is harder with Xojo’s co-operative threading but could still happen if a yield occurred at the wrong time.

1 Like

The sync methods exists to control such things… CriticalSection, Semaphore, Mutex

They do exist but they have to be used wisely otherwise you lose the benefit of the optimisations that STATIC would provide.

It also means that you have to design functions taking into consideration that this could happen which I imagine the majority of users wouldn’t.

Of course. That’s why programming is not the same as selling bananas. :smiley:
Threading is not for everyone. It’s in the “Advanced topics” in any language. :wink: