Ramblings of an Idle Mind: Frolic through the playground of my mind

Optimizing Code Reusability and Minimizing Your Footprint

One of the most common questions I am asked is also one of the biggest problems I see in code as I read it: lack of optimization. I often have people asking questions about how they can consolidate the generic actions they want multiple objects to have access to perform without duplicating the code. In Actionscript, just like any other coding language, the duplication of code is typically a red flag that you are doing something wrong. No, not wrong in the sense of broken, but wrong in the sense of best practice and code optimization. It is much easier to have one handler function to debug and keep up than to have that same handler individually executing in a dozen different class objects.

Quite possibly the single most useful thing I have discovered in optimizing some of the graphical effects I use over and over again is simply making use of the event object in my callback functions. When you attach an event listener to an object and the event is triggered, the event passed into the callback function has a target attribute that is a reference to the object which initially triggered the event. Accessing the object this way lets us generalize handlers (such as a fadeOut function) that will consolidate our code and give us uniformity in execution.

Let’s look at a simple example. Say that, throughout the course of a script’s execution time, we have a few dozen objects we want to fade out, and rather than having each type of object have its own fadeOut method, we just want to use a single handler for it. Well, this is exactly where the Event.target property comes in. Take a look at the following example, and then review the code for an easy reference example. We are randomly creating objects all over the stage, but they all immediately attach a generic listener for their ENTER_FRAME event. That fadeOut method simply takes whatever object it was called from and executes its code, finally cleaning up the event listener from the target object once the alpha has been faded successfully.

As you can see, the single fadOut method readily will handle any type of object at all that is thrown at it. Because we use the target property instead of a specific handler, we can generalize the actions performed and assign it to any valid object. Using this simple attribute of our events, we can begin to consolidate a lot of our code. Feel free to review the code and play with it as well. As always, let me know if you have any questions or suggestions for improvement on concepts!

Download Full Source

  • This article is very interesting. I have always previously put all my methods exclusively with the objects or classes that used them. I’m sort of starting to understand why this way works better.

    Thanks a bunch.

You can follow any responses to this entry through the RSS 2.0 feed.