« Object Literals | Main | Another improvement related to 'var'. »
Monday
Nov292010

Definite assignment

Another new feature to alleviate headaches: Definite assignment analysis.

Definite assignment analysis ensures that no variable is used before it has been assigned a value. This can prevent some subtle bugs, and will in general make code more clear. It is inspired by languages like Java and C#.

Consider this code:

var x : String;
if (a>10) x = "Hello";
else if (a<10) x = "Goodbye";
alert(x);

There may be subtle bug in this code. What if a has a value which is exactly 10? In that case, x will never be assigned a value, and the undefined value will be sent to the alert function.

Now, that may or may not be a bug depending on the intentions of the developer. However it is easy to miss that the variable in some case will never be assigned a value.

In the newest Mascara, you will for this reason get a compiler warning on the last line, because x may not be assigned a value at that point.

The right way to fix the code depends on the intention. If the if branches were supposed to cover all eventualities, then add an else or change the else if into an else.

If the variable should be null if no of the conditions are met, then just initialize it to null in the first line. (The null value is somewhat equivalent to the undefined value. However, there is the important difference that null indicates that a legitimate variable has been explicitly assigned the null value, while ‘undefined’ usually indicates an error or missing variable.)

To be clear, this improvement is not a part of the ECMAScript spec, it is a Mascara-specific extra verification. It will probably never be part of the ECMAScript because of backwards-compatibility issues. As always, I appreciate feedback on this feature.

PrintView Printer Friendly Version

EmailEmail Article to Friend