Why the superclass's createChildren() should be called last

In a conference somewhere, I had said that a Flex component should call its superclass's createChildren last, after it's done creating its own children. I don't think I got a chance to explain why.

Some Flex components expose their internals as protected properties. For example, you'll see that the Panel class has a protected titleBar property, which refers to the title bar of the panel. In the Panel class's createChildren, you'll see that it checks to see if titleBar is null before creating one.

if (!titleBar)
{
    titleBar = new UIComponent();
    titleBar.visible = false;

...

Why does Panel expect titleBar to ever be non-null? That's the whole point of making it protected in the first place -- so subclasses can create their own titleBar if they want.

Now of course this brings me to why the superclass's createChildren should be called last as a general practice: so that, by the time you call that superclass method, you've definitely created any children, including any children that the superclass might have otherwise created on its own. Makes sense?

So, here's what my Panel subclass, TotallyAwesomePanel, might look like:

override protected function createChildren():void
{
    if (!titleBar) {
        titleBar = TotallyAwesomeTitleBar();
        titleBar.visible = false;

        rawChildren.addChild(titleBar);
    }

    super.createChildren();
}

Two things here:

  1. We do a null check for titleBar ourselves. We can have subclasses too!
  2. We call the superclass's createChildren last, because we don't want the superclass to create another titleBar of its own (this can be harmful in some cases).

You do this a few times, in a few of your components, and it becomes a general practice. Even if you aren't overriding any of your superclass's properties (the way TotallyAwesomePanel above does), it doesn't hurt to create your own children before your superclass.

One Response to “Why the superclass's createChildren() should be called last”

  1. [...] Adobe Flex framework has God Objects, UIComponent is one those. [...]