Wednesday, December 7, 2011

Static Variables in Web Edition

Static variables can be a valuable thing, but there is a downside that you should be aware of when using them in Web Edition.

The Real Studio documentation for Static says:

"A variable declared with the Static statement and assigned a value retains its value from one invocation of the method to the next." (Click Here)

Static variables persist across subclasses as well, so if you have a method in a class that uses a Static variable, all of the subclasses will share that variable's value.

So what's so special about Real Studio Web Edition? Well, each end-user session is technically a subclass of the individual Webpages and other items you created in the IDE. Using Static variables may have unintended results.

For example: If you use a variable as Static in the WebPage1.Resized() event like this:

Event Resized()
  //Initialize the Static Variables
  Static LastWidth as Integer = Self.Width
  Static LastHeight as Integer = Self.Height
  //Show a message if the window got smaller
  If Self.Width < LastWidth and Self.Height < LastHeight then
    MsgBox "The browser window just got smaller!"
  End If
  //Update the Static Variables
  LastWidth = Self.Width
  LastHeight = Self.Height
End Event

This will work fine as long as there's only one Session (like if you're testing in debug mode). Once there's more than one, they will all share the LastWidth and LastHeight properties and every time a one user's browser window is resized, LastWidth and LastHeight will be updated for all connected users.

Here's what happens: If User1 makes their browser smaller and gets the MsgBox and then User2 makes their browser window smaller they will only get the MsgBox if the window is smaller than that of User1. Whichever user resized last, the dimensions of their browser is what is left in LastWidth and LastHeight.

While this could lead to a hard to track down bug, imagine what would happen if you used a Static variable for a Password!

To avoid this problem, you should use properties of the class you are using (in this case WebPage1.LastWidth) or as a property of the Session itself.

When writing code for Web Edition, always remember that all of the Sessions are technically running the same exact program. Properties on Modules and the App class, Shared Class Properties and Static Variables will all be available to all Sessions.

No comments: