Other Peoples Code projects are always instructive because it gives me some insights and things to talk about. REALbasic is easy-to-use. I sometimes think it’s too easy-to-use because it lets people get away with a lot of things that aren’t necessarily good. Today, in my ongoing occasional series on things that new people have problems with in REALbasic we’ll talk about Windows.
REALbasic has strong typecasting and is very object oriented, but Windows are a prime example of an object that can quickly get new developers into trouble. Take this bit of code:
if myWindow.visible = true then myWindow.visible = false end
What the user was TRYING to do was keep the window from loading. Unfortunately, what he was doing was loading myWindow and then making it invisible regardless if myWindow had been created previously. What the user should have done was something like this to see if that window has been created already:
for i as integer = 0 to windowcount-1 if window(i) isa myWindow then //do something special here return end next
What is this? Windows are special objects in REALbasic. They can be called without explicitly calling the ‘new’ statement. For example, the following two pieces of code do the same thing:
dim w as new myWindow w.show
The first one uses the implicit instance of a window, meaning that if you call it, myWindow gets created if it’s not already created and shows it. The second bit of code creates a new instance of myWindow and then shows it. In the first bit of code you can call this a million times and you’ll only get one window. The second example will let you create as many windows of myWindow as you have memory for.
Real Software introduced the ImplicitInstance property in RB 2007 R4 and, to me, this should be false by default (I wish it were a preference setting). Turning this property off and compiling will immediately tell you if you’re accessing the properties/methods/constants of the window definition rather than the instance of the window.
Look at it another class as an example. This code will fail:
dim d as date d.totalseconds = 123412354
Why does it fail at runtime with a nil object exception? Because d is a date object and it hasn’t been created yet (i.e. d is nil). The following code will work because d, the date object, has been created using the new command:
dim d as new date d.totalseconds = 123412354
The fact that windows can be created implicitly is both a feature and a hindrance. Turning off the implicitinstance property in your windows may just save you some time in tracking down window issues.
A good friend of mind said, “If you’re using the implicit instance, you’re code is broken – you just don’t know it yet.” While it’s somewhat of an exaggeration it’s advice well worth listening to. Treat your windows like classes and you’ll have fewer problems.