« YouTube's Hidden Anger for the Play Button | Main | Aftermixing at Brightcove »

Using Asserts In Flex

I find myself using assertions all the time in my Flex classes and am curious if others do the same thing. Along with a logging system (to turn tracing on and off), and some unwritten unit tests, I find the asserts to be the most helpful tool for keeping myself sane as my current project keeps growing.

Here's a good explanation of asserts for C++ and here's one for Java. I tend to use assertions in a lot of complicated AS classes or really any place where I expect something not to happen (since, of course, that impossible thing eventually does happen).

So do you need an Assert class? It's not hard to add one to your project. Here's a simple class that will work. You may need to modify it to show an alert if you're catching a lot of errors.
public class Assert
  // call enabled before calling assert().  This value is 
  // usually tied to a constants file where the value 
  // can be tokenized and turned off in production
  public static const enabled:Boolean = true;

  public static function assert(assertion:Boolean, 
      msg:String = null):void
    if (! assertion)
      throw new Error("An assertion failed" + 
          (msg ? (": " + msg) : "."));

Comments (4)

Now what would be great is if these assert calls could somehow be preprocessed/compiled out of production code.

We use Asserts extensively in our codebase. Recently we added a call to enterDebugger() to the Assert, so that when you are running in a debug build, it drops you right into the debugger.

David, thanks for the tip! I didn't know about enterDebugger().

Manish, I would love to see that as well. Actually, I'd like to see a general compiler feature where code inside of a false "if" test (where the the false is represented by a const) is removed. Then I could have asserts, traces, debug code, etc removed from my code. I haven't heard of any talk of such a feature, but I wouldn't be surprised if it was talked about on the compiler team.

Tyler Patterson:

Flex supports conditional compilation. Here is an example of how to do asserts that don't get compiled into production code.