ActionScript, Flash, and Flex
Invoking Constructors
RJ Regenold and I were discussing last night how we both strongly believe constructors should have extremely limited algorithms that simply invoke protected methods.
For instance, PureMVC’s Facade initializes the instance in the constructor
package org.puremvc.as3.multicore.patterns.facade
{
import org.puremvc.as3.multicore.core.*;
import org.puremvc.as3.multicore.interfaces.*;
import org.puremvc.as3.multicore.patterns.observer.*;
public function Facade( key:String )
{
if (instanceMap[ key ] != null) throw Error(MULTITON_MSG);
initializeNotifier( key );
instanceMap[ multitonKey ] = this;
initializeFacade();
}
}
package org.puremvc.as3.multicore.patterns.facade
{
import org.puremvc.as3.multicore.core.*;
import org.puremvc.as3.multicore.interfaces.*;
import org.puremvc.as3.multicore.patterns.observer.*;
public function Facade( key:String )
{
if (instanceMap[ key ] != null) throw Error(MULTITON_MSG);
initializeNotifier( key );
initializeInstance();
initializeFacade();
}
protected function initializeInstance():void
{
instanceMap[ multitonKey ] = this;
}
}
I would even argue that the Error checking / validation takes place in an init of some kind as well.
Another example is as follows
Instead of doing,
package
{
import flash.display.Sprite;
public class ViewUI extends Sprite
{
public function ViewUI()
{
super();
width = 100;
height = 200;
}
}
}
Do this
package
{
import flash.display.Sprite;
public class ViewUI extends Sprite
{
public function ViewUI()
{
super();
init();
}
protected function init():void
{
width = 100;
height = 200;
}
}
}
This practice becomes increasingly important in open-source projects. Moreover, this example may be limited but consider more complex constructors that you’ve seen or written yourself. The construction process should be divided into segments when possible.
UPDATE ( 01.13.10 ): Bill Sanders recently posted a good article about this exact topic!
Popularity: 23% [?]
| Print article | This entry was posted by johntimothybailey on November 26, 2009 at 12:04 pm, and is filed under ActionScript, Architectural Pattern, Programming Practice. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 2 months ago
http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/