views:

134

answers:

2

I have a variable, and a function for brevity lets consider it looks like this:

private function applyDiscount (value:Number):Number
{
return value*_discount; //_discount defined somewhere else
}

OK thats all fine and dandy but say I want to be able to call that function and be able to pass my own discount, but still use the _discount as a default.

I CAN do this:

private function applyDiscount (value:Number, discount:Number = 50):Number
    {
    return value*discount;
    }

This will make discount default to 50 but I don't know it at authortime so I need to do this but its not allowed in Flex.

private function applyDiscount (value:Number, discount:Number = _discount):Number
    {
    return value*discount;
    }

So my question is, what is the best way to achieve the same as the last example in Flex?

Thanks.

+1  A: 

Maybe have the discount exposed as a public property so you can set it separately to the method call. e.g

public function get discount():Number{ 
    return _discount; 
} 

public function set discount(param:Number):void { 
    _discount = param; 
}

private function applyDiscount (value:Number):Number
{
    return value*_discount; //_discount defined somewhere else
}

The additional function looked goofy in the comments so I have added it here... Basically you could make the discount an optional parameter.

function applyDiscount(value:Number, ... rest):void {
    if(rest.length > 0) {
        return value*rest[0];
    } else {
        return value*_discount; //_discount defined somewhere else
    }
}

applyDiscount(100, 10); // 10 discount...
applyDiscount(100); // default discount...
Fraser
Well I actually have 2 discounts though, the primary discount, and then during promos an additional discount, and I need to display the original price, discounted price, and extra discounted price to the user.
John Isaacks
Hm that is not what you asked... In any case you could make the discount an optional parameter. e.g.function applyDiscount(value:Number, ... rest):void { if(rest.length < 0) { return value*rest[0]; } else { return value*_discount; //_discount defined somewhere else }}
Fraser
+4  A: 

private function applyDiscount(value: Number, discount : Number = Number.POSITIVE_INFINITY){
   if(discount == Number.POSITIVE_INFINITY) discount = _discount;
    return value*discount;
}
ForYourOwnGood
Probably more a style choice, but I usually prefer NaN for default arguments that will be replaced like that. Conceptually, it's closer to null (which people generally use for non-numeric defaults of the same style).
joshtynjala