Be careful how you call super()

Here’s something all ActionScript 3 developers should know about extending classes and how parent constructors are called:

If class B extends class A, does class B have to call super() in its constructor in order to instantiate the parent class? Nope. What happens if you don’t? The compiler inserts a call to the constructor for you. Usually.

The compiler just looks to see if you call super() at any point in your constructor. What if that call is inside of a conditional statement that evaluates to false? The default constructor won’t get inserted, and the parent classes’s constructor won’t get called. Why is that a problem? You may very well get null reference exceptions since class level variables are often initialized in constructors. What’s worse, you may only get them sometimes — only when your conditional statement evaluates to false.

Even if you determine that your code works whether super() is called or not, you still have to watch out. What if the implementation of the parent classes changes in the future? Code that used to work, and code that you could reasonably expect to continue working, may just break on you. I’ve actually seen this happen. It’s not pretty.

How do you avoid this problem? Either call super(), or don’t. Never put super() in a statement that may not execute, even if you find that your code works fine today since you never know what might happen to that parent class tomorrow.