Magic Strings vs Constants

In looking at pieces of the MM framework, and how a lot of developers write their own code, I’ve noticed a lot of magic string usage. What do I mean by a magic string, let’s examine the following piece of code for a definition:

myComponent.addEventListener("change", this);

In this example, “change” is the magic string. The reason that it is a magic string is that code is dependent on that string being correct, but yet there is no formal assertion that it is correct. For example, if in the example I mispelled “change” as “chnge”, my code would fail silently. Though this may not be catastrophic, you are left to your own debugging methods to figure out what went wrong. Fortunately, there are several ways to remedy this. The easiest and most common is to implement some sort of constant variable in your code to represent the string. For example:

// definition : mx.controls.ListBox.EVT_change = "change";
myComponent.addEventListener(mx.controls.ListBox.EVT_change, this);

In this example, the dispatching object actually has a static property EVT_change that is equal to the string and which is used to represent the string. If you use this method and type in a property that doesn’t exist, you will get an error. So with little effort you can have strict typing, better debugging, and more relaxation time.


  1. JesterXL

    Yeah, I’ve been replacing attachMovie and contentPath with that:

    popup = Window(PopUpManager.createPopUp(this, Window, true));
    popup.contentPath = “SomeForm”;

    instead becomes:

    popup = Window(PopUpManager.createPopUp(this, Window, true));
    popup.contentPath = SomeForm.symbolName;

    Since in the UIComponet you define those variables, you can get syntax checking. I hope EventDispatcher most to this model in the future as does all the framework.

  2. Kenny Bunch

    Good example Jesse. That is one that people using components should recognize as a best practice I think.

  3. Byron

    Good reminder here. I usually think of this as a better way to do things but didn’t think about compile time vs runtime.

    One thing – it should probably be Magic Strings vs Constants since you really are talking about constants which are general term. Also, in most languages “change” is still strictly typed – it’s a string.

  4. Kenny Bunch

    Yea, I meant to title it that, but published befre noticing and didnt know if it would in effect make it a new post in aggregators.. I just changed it anyways to see.

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">