TweetFollow Us on Twitter

Object-Oriented Programming with REALbasic

Volume Number: 20 (2004)
Issue Number: 4
Column Tag: Programming

REALBasic Best Practice

by Guyren G Howe

Object-Oriented Programming with REALbasic

Getting the most from a unique Object-Oriented paradigm

Welcome to the first issue of my regular REALbasic Best Practice column. Each month, I'll tackle the question of how one can get the most out of REALbasic. I'm going to mix things up: reviews, advice, adapting general programming techniques to REALbasic, but always with the theme of "best practice".

I'm going to start with something I touched on in last month's review: REALbasic's unique object-oriented programming feature, that I call the Event Model. This article assumes you are familiar with the basics of object-oriented programming.

A Little History

A little history will help us to understand where we are.

REALbasic's original designer, Andrew Barry (who sadly is no longer with REAL Software) came up with what I believe is an entirely novel, and powerful object-oriented programming model for the very first version of REALbasic, which he prosaically called Events. To distinguish this feature in general from particular events, I'll call the feature the Event Model.

Because it was too different from what folks were used to, and because it made porting code from other languages more difficult, Andrew bowed to pressure, and also provided support for basically the same OOP model that Java supports (single inheritance with interfaces).

Once Andrew left, the programmers and managers at REAL Software have, to my mind, quite reasonably focused on the many other ways in which they wanted to improve REALbasic, and they've done a bang-up job of that. But they have, in some ways unfortunately, lost focus on this cool language feature. It's still there, it still works just fine, but REAL doesn't correctly document it, they don't much talk about it, and they haven't extended it in a few obvious ways that would make it just about perfect.

Why You need events

You need the Events Model because it makes code development and maintenance easier, and because the result of code changes in a superclass under the Events Model is much more predictable than with traditional method overriding.

In fact, the Event Model brings such clarity, and maintainability benefits that, except for doing one particular thing, Events are superior in every way to traditional method overriding.

Events vs Method Overriding

I will now explain what the Event Model is, and provide an example to demonstrate the advantages I just mentioned.

What we're about here is the relationship between the code in a superclass, and the code in a subclass. In Object-Oriented Programming languages, one of the most interesting problems is how the language should support code re-use down through a class hierarchy. We want to be able to provide some code in a superclass, and then have code in a subclass somehow extend or modify that code -- and to perform further modification, and extension of behavior on down a class inheritance chain.

Every mainstream Object-Oriented language does this by allowing a subclass to override methods on its superclass, entirely replacing that code, and then allowing the subclass to invoke methods defined in the superclass, including quite often invoking the superclass's version of the overridden method. A common pattern will be a method on a superclass that provides code to complete some but not all of some task, with the expectation that a subclass will override the method, carry out the rest of the task, and at some point call the overridden method to do the common part.

Notice that in this scheme, the subclass is entirely in charge of the final carrying-out of the method. In particular, it is up to the subclass to determine when and how to invoke the code in the superclass as part of its design for the complete method. In an inheritance chain, control is usually passed in this way from the bottom up, with a subclass invoking the most immediate superclass's methods as it desires.

There are two serious problems with this model:

Good object-oriented design will push as much code as is reasonable toward the top of the class hierarchy, but that code has to be written without being able to rely on when and how it is being invoked by the subclasses. Even in code you're entirely writing yourself, you have to remember what conventions you intended to employ in this relationship, possibly when you come back to code six months after you wrote it; and

It is easy for a subclass to override a superclass in such a way that, although you want to make a change in behavior that is the superclass's responsibility, you can't do it without also having to change some or all of the subclasses' code as well.

The Events Model, on the other hand, turns this whole thing on its head, allowing the superclass to provide subclasses with explicit opportunities to act, and letting these opportunities pass down the inheritance chain rather than up it. This very neatly avoids both of the problems mentioned, as we will see.

An Example

Let's consider a simple example that clearly illustrates the advantage of the Events Model.

Assume we're writing an application with a non-standard user interface, so we use custom controls drawn using graphics primitives.

We create an abstract Control superclass, whose task it is to keep track of where the control is on the screen. We give it a Draw method.

Next, we have an abstract Button subclass of Control, with code to draw a common background color and some other graphic details shared by all the buttons in the program.

We then create a whole variety of button subclasses for various tasks.

So we have an inheritance hierarchy that looks like this:


Figure 1: A simple inheritance hierarchy

The Method Overriding Way

When we use method overriding as our means of extension, as we go up the chain, each class overrides its superclass's Draw method and invokes that method as part of its own draw process.

This means that a control at the bottom of the chain will have a Draw method that looks something like this:

Pseudo-code for a Draw method at the bottom of the inheritance chain

Sub Draw
   Super.Draw
   ... code to draw specifics on top of background provided by super
End Sub

Button.Draw, in turn, has code like this:

Pseudo-code for Button.Draw
Sub Draw
   Super.Draw //Work out where I'm drawing
   ... code to draw background
End Sub

Control.Draw has code like this:

Pseudo-code for Control.Draw
Sub Draw
   ... code to work out where to draw
End Sub

This is all fine. We get nice abstraction and code re-use, all the usual OOP goodness.

But a problem arises when we make changes to the superclasses. Let's say we now want to make all our buttons have an Aqua-style highlight: we want to take whatever the subclass produces, and run a graphic filter over that to make it look like it's sitting in a drop of liquid.

We simply can't do it without wholesale code rewriting. With this inheritance scheme, the superclass has no way to obtain another chance to act after the subclass is done calling on it. The only solution is to make changes to every bottom-level subclass, even though we really don't need the subclasses to do their part of the drawing task any differently. A change in the shared logic can't be implemented in the shared code.

The Event Model

An Event declaration is essentially a declaration of the interface for a method that subclasses can implement (this "method" is called an Event Handler), that can only be called from the declaring superclass. Once declared, the superclass can invoke the event handler just like a regular method or function.

When an event handler is called, the most immediate subclass implementing a handler for it gets to act. If no subclass implements a handler, the call is ignored (if the call is to a function, a "null" -- 0, Nil, False, the empty string, and so on -- value is returned).

Note that once a handler for an event exists in the hierarchy for a particular class, further subclasses don't even see the event. Frequently, the subclass will do whatever it needs in response to the event invocation, and then invokes a new event it has declared, having exactly the same name and arguments, providing further subclasses with the opportunity to act.

Note that rather than the ill-defined mess that is method overriding, the language is providing a well-defined protocol for superclasses to delegate specific responsibilities down to their subclasses.

A good example of this scheme is the REALbasic EditField control, which declares a KeyDown event as a function with a string argument, returning a Boolean value. The event indicates to a subclass that the user has tried to type something into the EditField. If the subclass provides a handler for KeyDown and returns True in that handler, the keystroke is ignored. Otherwise, it is displayed in the EditField normally.

This scheme makes it easy to extend the EditField to create a control that, say, only lets the user enter a number.

The Button Example, Using the Event Model

Back to our example of custom buttons.

Under the Event model, rather than each subclass overriding its superclass's version of Draw, only the top-level Control class has a Draw method. In addition, Control declares a new DrawEvent event. Each subclass will provide a handler for the event, and will also declare a new version of the event, calling it at the appropriate time. So now we have:

Control.Draw has code like this:

Pseudo-code for Control.Draw
Sub Draw
   ... code to work out where to draw
   DrawEvent //Ask subclass to now draw itself there
End Sub

Button's DrawEvent handler looks like this:

Pseudo-code for Button.Draw
Sub DrawEvent
   ... code to draw background
   DrawEvent //Ask subclass to draw its content atop the background
End Sub

Finally, the class at the bottom of the chain just does its part of the task.

Pseudo-code for a Draw method at the bottom of the inheritance chain
Sub DrawEvent
   ... code to draw specifics on top of background provided by super
End Sub

Now what happens when we want to add the new graphical tweak? We only have to change the code in one place, Button's DrawEvent handler, which now looks like this:

Pseudo-code for an extended Button.Draw

Sub DrawEvent
   ... code to draw background
   DrawEvent //Ask subclass to draw its content atop the background
   ... code to draw water on top
End Sub

Once you get the Event Model, you miss it in every other object-oriented language.

There are many advantages to the Event Model. For example, if you're working with a team of programmers, or you're shipping a framework for others to use, with method overriding, you need all sorts of tortuous documentation about how subclasses should interact with their superclasses. With the Event model, the language itself enforces the relationship. So not only does the Event Model make maintenance easier, but it better explicates the logic of the program.

The Exception that Proves the Rule

...except that there is one feature for which we still need overriding: functions for which the subclass should return a more specific type than the superclass does. The canonical example of this is a generic data structure. We can write, say, a generic data store base class that stores Objects. But this is needlessly difficult to use as it is, because we have to cast the objects we get from it to a more specific type in order to use them, every single time we use this class.

What we want is to extend the generic data structure to one storing objects of more specific types -- a list of controls, for example, where the casting to the correct return type is done for us. Unfortunately, the Events Model provides no way to do this, because the function that yields the objects must be declared to return values of type Object (or perhaps Variant).

The method overriding paradigm provides what we need here. We create a Protected function toward the top of the inheritance chain, then declare and invoke suitable events so that subclasses can carry out the function. Then we create a 'public face' on that function in the bottom-level class in the form of a function that returns the type we want, and have it just call up to the protected internal function, at the top of the class hierarchy, that provides the generic functionality.

So the call sequence goes like this:


Figure 2: Using Method Overriding to Create a More Restricted Type

We invoke the public Get() function on the bottom-level ControlStore class.

ControlStore invokes the protected GenericStore.GetInternal() function on the base GenericStore class.

GenericStore invokes its GetEvent.

The most immediate subclass declaring a handler is GenericList, which fetches the result, returning it to GenericStore.

GenericStore returns the result to ControlStore.Get().

ControlStore.Get() casts the result to a Control and returns it to the original caller.

Interestingly, notice that in a sense, we aren't actually extending the GenericList class's behavior: we're actually restricting it. All of this calling up, and back down the inheritance chain is a little weird when you first do it. Quite often, in the bottom class, you will be creating the public function, calling the protected version in the base class, then turning around and handling the event again the same bottom-level class. When I first started doing this, it felt a bit baroque, to be going up, and then down the inheritance chain like this, and having the public function actually fulfill its role in the event handler. But I'm quite comfortable with it now because I don't see overriding as an extension mechanism at all any more.

It might help to see that in fact, you could do this with just Events by creating a wrapper class that does the type casting. I just prefer to do it all within the same class hierarchy, because it's cleaner and clearer to do this rather than create the generic store, the wrapper class, and suitable Interface.

It would be nice if REALbasic had templates, or if some other mechanism could be found that let us stick entirely to the Events Model without any of that, but this constrained use of overriding is just fine for now.

Improvements Wanted

I'd like to see REAL Software emphasize the Events Model in their documentation. I'd also like to see them look into making some improvements to the Events Model to make it more powerful.

One obvious improvement would be to provide a compiler directive that could execute different code depending on whether an Event has a handler available or not. A common style of programming you'll want to do with Events is to provide default behavior at some point in the code for a class, but allow a subclass to extend or replace that behavior (as the EditField does with the KeyDown Event).

The only way to do that right now with Events is to call a function-style Event Handler, and do your default behavior if you get back the "null" response. But in some circumstances, you need to treat the null value as a result, rather than an indication that you didn't provide an event handler, and you wind up doing all sorts of gymnastics to work around the problem.

Conclusion

I hope I've convinced you of the virtue of the Events Model. Once you "get it", in my experience, you'll wonder how you ever lived without it.


Guyren G Howe works in artificial intelligence research, after years of work as a technical writer and developer. He is married with one child, is an Australian, and lives in Austin, Texas. Guyren has been working with REALbasic for several years. Most notably, he wrote the REALbasic Curriculum Project, an extensive computer science curriculum, for REAL Software (available from the REALbasic website).

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

iClock 4.6.4 - Customizable menu bar clo...
iClock replaces the old Apple's default menu bar clock with more features, customization and increases your productivity. Features: Have your Apple or Google calendar instantly available from the... Read more
Final Cut Pro X 10.4.5 - Professional vi...
Final Cut Pro X is a professional video editing solution. Completely redesigned from the ground up, Final Cut Pro adds extraordinary speed, quality, and flexibility to every part of the post-... Read more
MarsEdit 4.2.6 - Quick and convenient bl...
MarsEdit is a blog editor for OS X that makes editing your blog like writing email, with spell-checking, drafts, multiple windows, and even AppleScript support. It works with with most blog services... Read more
Microsoft Office 2016 16.16.6 - Popular...
Microsoft Office 2016 - Unmistakably Office, designed for Mac. The new versions of Word, Excel, PowerPoint, Outlook, and OneNote provide the best of both worlds for Mac users - the familiar Office... Read more
calibre 3.38.0 - Complete e-book library...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
Microsoft Office 365, 2019 16.21 - Popul...
Microsoft Office 365. The essentials to get it all done. Unmistakably Office, designed for Mac Get started quickly with new, modern versions of Word, Excel, PowerPoint, Outlook and OneNote-... Read more
Microsoft Office 365, 2019 16.21 - Popul...
Microsoft Office 365. The essentials to get it all done. Unmistakably Office, designed for Mac Get started quickly with new, modern versions of Word, Excel, PowerPoint, Outlook and OneNote-... Read more
Microsoft Office 2016 16.16.6 - Popular...
Microsoft Office 2016 - Unmistakably Office, designed for Mac. The new versions of Word, Excel, PowerPoint, Outlook, and OneNote provide the best of both worlds for Mac users - the familiar Office... Read more
Final Cut Pro X 10.4.5 - Professional vi...
Final Cut Pro X is a professional video editing solution. Completely redesigned from the ground up, Final Cut Pro adds extraordinary speed, quality, and flexibility to every part of the post-... Read more
calibre 3.38.0 - Complete e-book library...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more

Latest Forum Discussions

See All

Pre-register now for epic fantasy RPG Fi...
Final Blade is an epic fantasy RPG that revolves around two warring nations and one extremely powerful sword. Having already found great success in Taiwan and South Korea, the developer is now bringing its acclaimed free-to-play iOS and Android... | Read more »
The top 3 best iPhone and iPad games com...
The end of the week has rolled around. It's been a pretty good seven days for mobile gaming - if you want proof you can click here and check out our five favorite games that came out this week - but now we're going to turn our attention to the... | Read more »
The best games for iPhone and iPad that...
Every week here at 148Apps we like to make sure that you're up to date with all the awesome games that have come out for iPhone and iPad over the past 7 days. We pick the cream of the crop to ensure that you don't have to play anything boring and... | Read more »
The top 3 best idle games for iPhone and...
Sometimes you want to play a game where you don't really have to do anything. Don't worry, we're not here to judge you, we're exactly the same. We love some action when we're in the right mood, but sometimes we want something a little more chill -... | Read more »
The top 5 best games with great stories...
Last week we took a look at the best games for iOS that you could waste hours and hours of your life playing, so now we thought we'd have a look at the top 5 games for iPhone and iPad that have great stories. These are the tales that have stuck... | Read more »
Langrisser Mobile preview - Seminal TRPG...
Langrisser Mobile is set to finally break the revolutionary TRPG franchise's 20 year silence when the it finally makes its way to touchscreens the world over at the end of the month. The original Langrisser game (known as Warsong in the west)... | Read more »
Everything you need to win at Dragalia L...
Want to up your Dragalia Lost game? You've come to the right place. Here at 148Apps, we've been digging deep into Nintendo's latest gacha game to find the best tips, tricks, and strategies to share with all of our future co-op team mates (read: you... | Read more »
How will World of Warcraft, Starcraft, a...
You might have heard that Blizzard is bringing Diablo to mobile with Diablo Ultimate. There's been plenty of controversy surrounding that decision, and it's meant that a really important piece of information has been glossed over a little. Namely... | Read more »
The top 3 best iPhone and iPad games com...
Our mission here at 148Apps is pretty simple - we want to make sure that you're playing the best iPhone and iPad games in the world. Which is why, every Friday, we like to give you an insight into the incredible games that are set to rock your... | Read more »
The top 5 best games for iPhone and iPad...
It's been a pretty decent week for releases on the App Store, all told. This week has the feeling of a mobile-first start to the year, with developers releasing games that fit perfectly in the palm of your hand. And we've picked what we think are... | Read more »

Price Scanner via MacPrices.net

New US Cellular iPhone deal: Switch and get a...
US Cellular has introduced a new deal offering free or discounted Apple iPhones to new customers. Switch to US Cellular and get a 64GB iPhone Xr for free or get a 64GB iPhone Xs or Xs Max for 50% off... Read more
20% off iPhones with plan at Total Wireless w...
Use coupon code TWNEWYEAR20 at Total Wireless from January 5, 2019 to January 31, 2019, and take 20% off their selection of new iPhones or other devices. Total Wireless plan is required, and the... Read more
Price drop! B&H now offering all new 27″...
B&H Photo has lowered prices on new 27″ Apple iMacs, and they’re now offering each model for $200 off MSRP, starting at $1599. These are the same models offered by Apple in their retail and... Read more
B&H has Apple Watch Series 3 GPS + Cellul...
B&H Photo is discounting Apple Watch Series 3 GPS + Cellular models by $60-$70, with 38mm Watches starting at $309. Shipping is free: – 38mm Apple Watch Series 3 GPS + Cellular: $309 $70 off MSRP... Read more
Get a 32GB iPhone 6s at Boost Mobile for $299...
Boost Mobile is offering the 32GB Apple iPhone 6s and 6s Plus for $150 off MSRP plus a free $100 account credit. Their discount reduces the cost of a 32GB iPhone 6s to $299.99 and the 32GB iPhone 6s... Read more
Get a new 9.7″ Apple iPad for $75 off at Veri...
Use coupon code TABLET75 at checkout to save $75 on a 9.7″ iPad at Verizon for a limited time. This reduces the price for the 32GB model from $459 to $384 and the 128GB iPad from $559 to $484. New... Read more
Sale! B&H Photo drops prices on 13″ MacBo...
B&H Photo has new 13″ MacBook Pros on sale for up to $150 off MSRP, valid through January 16, 2019. Their prices are the lowest available for new 13″ MacBook Pros from any Apple reseller. These... Read more
Lowest prices ever on new 2018 11″ Apple iPad...
B&H Photo has new 2018 Apple 11″ iPad Pros in stock today and on sale for $50-$100 off MSRP. Shipping is free. These are the same iPad Pros offered by Apple in their retail and online stores. B... Read more
Sale! Get a new 27″ Apple iMac for $100-$200...
B&H Photo has new 27″ Apple iMacs on sale for up to $200 off MSRP. These are the same models offered by Apple in their retail and online stores. Shipping is free: – 27″ 3.8GHz 5K iMac (MNED2LL/A... Read more
Get a refurbished 2017 12.9″ iPad Pro for up...
Apple has Certified Refurbished 2017 12″ iPad Pros available for $120-$190 off original MSRP, depending on the model. An Apple one-year warranty is included with each model, outer shells are new, and... Read more

Jobs Board

Best Buy *Apple* Computing Master - Best Bu...
**667840BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Sales **Location Number:** 000456-Woodbridge-Store **Job Description:** **What does a Read more
*Apple* Enterprise Engineer - Evolver, Inc....
…contribute to the success of the company. Evolver is seeking an Apple Enterprise Engineer to work in Washington, DC Responsibilities: The successful candidate Read more
Geek Squad *Apple* Master Consultation Agen...
**667848BR** **Job Title:** Geek Squad Apple Master Consultation Agent **Job Category:** Services/Installation/Repair **Location Number:** 000531-Portland-Store Read more
Best Buy *Apple* Computing Master - Best Bu...
**665166BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Sales **Location Number:** 000868-West Lebanon-Store **Job Description:** **What does a Read more
Geek Squad *Apple* Master Consultation Agen...
**667309BR** **Job Title:** Geek Squad Apple Master Consultation Agent **Job Category:** Services/Installation/Repair **Location Number:** 001008-Vacaville-Store Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.