« HTML5 for Web Designers | Main | 20x2x20 Week 1 »

Optional int

I've recently run across the need to have a optional int field. That is a property on a class that is of type int but can be left unset (or null). AS3 doesn't provide the Java equivalent of the Integer class so I was curious what my options are. Below are four options that I played with. If you know of others leave a comment.

Option 1: type it as Number

public class Temp {
    public var value:Number;
}

Pro: Test if value has been set using isNaN(temp.value). No compiler warnings for assignment to another int and mathematical operations.
Con: Doesn't convey that the value is of type int. Allows user to set non integer values.

Tweak: Provide a get/set that downcasts the incoming Number to an int and possible throw ArgumentError if a non int value is passed.

Option 2: type it as *

public class Temp {
    public var value:*;
}

Pro: Test if value has been set using temp.value == null or temp.value == undefined. No compiler warnings for assignment to another int and mathematical operations.
Con: Doesn't convey that the value is of type int. Allows user to set anything.

Option 3: get/set/isSet

public class Temp {
    private var _value:Number;
    public function set value(value:int):void { _value = value; }
    public function get value():int { return _value; }
    public function isValueSet():Boolean { return !isNaN(_value); }
}

Pro: Test if value has been set using temp.isValueSet(). Clear that value is of type int.
Con: Bunch of code. Not a common AS3 paradigm

Option 4: Integer class

public class Integer {
    private var _value:int;
    public function Integer(value:int) { _value = value; }
    public function valueOf():int {return _value; }
}
public class Temp {
    public value:Integer;
}

Pro: Test if value has been set using temp.value == null. Clear that value is of type int and is optional. Safe to use in mathematical operations.
Con: No direct assignment to another int. Bigger memory footprint.

Note: The use of the valueOf() function makes the Integer class do the right thing in most contexts such as var sum:int = 12 + temp.value. You do need to use valueOf() when doing direct assignment var value:int = temp.value.valueOf();.

Conclusions

I can see each of these options working based on the situation. Out of all of them Option 1 is the most appealing from a minimal code perspective and is a typical AS3 paradigm. Wrapping the setting with a conversion of the Number to int improves correctness.

Tags: as3 flex

Comments

Maybe you didn't mention it because it's obvious, but… If the property is intended to represent an integer within a specific range (such as an unsigned integer), there's always the good ole' sentinel value, such as public static const MYVAR_DEFAULT:int = -1; public var myVar:int = MYVAR_DEFAULT;
I think I always end up with Option 1 after I play around with various approaches.