7) Best practices for Modular OOP in the Flash Platform

The sample class in Chapter 6 is probably too short and too basic to illustrate the real benefits of using the EventCollector class for managing all of your events within a Flash application.

In Chapter 3, we talked about managing "hundreds of classes". And inevitably, this leads us to think about how we design our applications on the Flash Platform. Remember what we said above: "The simplest ideas work the best." Bertrand Meyer introduced Modular OOP about 15 years ago [MEYER, 1997]. As everything has already been theorized, we just have to apply some of these concepts to make better software.

By combining modular design (consider classes as modules) and a few simple techniques, such as the EventCollector class, it should be possible to definitely close discussions about memory leaks on the Flash Platform. A base rule should be accepted by everyone:

Each time a main object is responsible for creating a strong reference in the memory to any other object, it should provide a visible mechanism for removing this reference.

This is a global concept, so "visible" means "accessible by the consumers of the main object".

For example, SPAS 3.0 API implements such a process through the finalize() methods. According to this, if we consider the sample class from Chapter 6, the deleteObj() method should be rewritten as shown below:

private function deleteObj():void {
    _evtColl.removeAllEvents();
    // Deletes all event listener references.
    evtColl.finalize();
    // Deletes all internal persistent objects used within the EventCollector instance.
    evtColl = null;
    // Deletes the EventCollector instance.
    _sprite = null;
    // All sprite objects can be garbage-collected and memory being free.
}

For a more global transcription, regarding ActionScript 3.0 practices, the original rule could be simplified to this one:

Each time a class instance is responsible for creating a BitmapData instance or an event listener, it should provide a public method for deleting the reference of this object.

Moreover, the logical name of such an action should be "destroy". And that is where the EventCollector class is really interesting to use, because we no longer need to pay attention to the event listener references we have created to delete them later. A single command is used to carry out this task:

public function destroy():void {
    _evtColl.removeAllEvents();
    _evtColl.finalize();
    _evtColl = null;
    // Write the rest of the destroying statement here...
}

By applying this code snippet to all of your developments, you could create much better reusable libraries, components or applications.