Browsing articles in "Design Patterns"
Feb 3, 2010

Making ActionScript Look Beautiful: Increasing Readability and Loosing Verboseness

After playing around with languages such as Ruby and Groovy, I’ve been yearning to loose a lot of the verboseness of ActionScript. I feel that many languages tend to be overly expressive, and hide the concepts of what your code is actually doing.

Lets take a simple example of a snippet of code that represents, Is tomorrow after today?

function isTomorrowAfterToday():Boolean
{
    var now:Date = new Date();
    var today:Date = new Date(now.setHours(0, 0, 0, 0));
    var tomorrow:Date = new Date(now.setDate(now.date + 1));
    return tomorrow.getTime() > today.getTime();
}

Continue reading »

Mar 10, 2008

Saving Flex’s Application State to a Database

Bill Sanders has a great post on the Memento design pattern over at his blog. After reading it, I thought I’d chime in and post a technique that takes the memento one step further. This approach allows you to serialize a Memento object into a ByteArray and save it into a database. Then, retrieving the Memento object from the server, dynamically instantiated it, and restoring its previous state.

One major draw back to the Memento, as you’ll see, is that restoring an object’s state can be a very expensive operation. Especially in a Flex environment where restoring a Memento could trigger a large display list invalidation. For that reason, the Memento is not always the ideal pattern for implementing undo/redo functionality. The alternative pattern for implementing this functionality is the Command pattern. With the Command pattern, each command is only concerned about a particular action to get to the current state of the application. With this, you can have an undo() method in each of your commands that undoes whatever action was performed in your execute() method. Continue reading »

Sep 24, 2007

When to Use Weak References

Understanding when to use a weak references, versus strong references can be a confusing one. It took me awhile to fully grasp when, and when not to use one over the other. On top of that, there’s very little documentation on the LiveDocs about the subject. Under the documentation for IEventDispatcher.addEventListener(), it states:

useWeakReference:Boolean (default = false) — Determines whether the reference to the listener is strong or weak. A strong reference (the default) prevents your listener from being garbage-collected. A weak reference does not.

And here’s what they have listed for the Dictionary’s constructor:

weakKeys:Boolean (default = false) — Instructs the Dictionary object to use “weak” references on object keys. If the only reference to an object is in the specified Dictionary object, the key is eligible for garbage collection and is removed from the table when the object is collected.

Ok … thanks. So, I did some Googling, and both Ted Patrick and David Coletta have much better information on the subject.

The basic idea behind strong references and addEventListener is this: when you call addEventListener and you pass it the function that you want to be called when the event fires, the event dispatcher is actually grabbing and holding a reference to that class and function it contains. As we all know, an object won’t be garbage collected until every reference to it doesn’t exist anymore. This insures that the event dispatcher always has a reference to the function that needs to be called. However, if you’re not careful, this can be a breeding ground for nasty memory leaks.

So, here’s my short list of do’s and don’ts related to strong vs weak references and event listeners:

  • Always use a weak reference when adding an event listener to a class that’s a singleton, or any object that you expect to live throughout the life of your application. Remember, this applies to most of Flex’s manager classes, including the SystemManager, and any event dispatching classes that your singleton’s contain.
  • Always use weak references when adding Cairngorm commands. The event dispatcher in Cairngorm is a singleton, and will always keep references to those command classes.
  • According to Ted, weak references are 10x slower. (True when referring to member access, but not event listening.)
  • It’s safe to use strong references when you’re adding an event listener to itself (i.e. the instance dispatching the event).
  • You should use a weak reference when adding an event listener to the Timer class.
  • Lastly, always make sure to clean up and remove any event listeners your classes are using when they’re no longer needed. I follow .NET’s approach, and I have an interface called IDisposable. This interface contains a single method called dispose(), and inside I remove any event listeners that the class might be using. Additionally, you could clean-up any BitmapData objects you might be using, among other things. Most, if not all, of my classes that I write implement this interface, and I just make sure to call dispose() when I know the object is no longer needed.

If there’s anything else to look out for, I’d love to hear them. It’s always good to be proactive when it comes to memory leaks.

Aug 31, 2007

The State Pattern in Flex 2

Photoshop Tools ThumbI’m currently working on Flex project at Quality Attributes Software that requires the use of a set of tools, similar to Photoshop, to manipulate a drawing canvas. Some examples of tools might be a drag tool, a selection tool, and a zoom tool. I thought to myself, “Ok, simple enough. Throw all the logic into a switch statement inside a generic on click button handler.” So, when a user clicks on a new tool, disable all the functionality from the previous tool, and enable the functionality of the new one. Ugh! This was a complete disaster. What happens when you expose all this logic, is that you run into some very highly coupled code. Meaning that each tool is essentially keeping the state of the other tools. Yuck!

There’s definitely a better way to handle these situations, and that’s by using the state pattern. Essentially, I turned each tool into a state. So when a user clicks on the Selection Tool, the program changes its state to use the functionality of selecting objects on the drawing canvas. I hide all this logic behind an interface, and each tool is represented as a class that implements this interface. If you’d like some code examples of this pattern, William Sanders has a great write up over at Adobe’s Developer Center.

About Dan

  • I'm the Lead Software Architect at Mixbook. A rapidly growing online photobooking and scrapbooking company.
  • I built Cayri, an online monitor for flight simulator networks.
  • I enjoy learning guitar, astronomy, beer, music, programming, and driving with no apparent destination.
  • I live in San Jose, CA.

Categories

Twitter