Hi, I'm getting fed up with crashes because of property type change between app release or bad data return in a JSON object from makeWebRequest, so I wrote the following two functions to deal with that (I have one for each main type (number, float, string and boolean). How would you improve upon it? I tried to make it generic instead of having one set per type I'm validating against but was unable to find a way. The validate can even handle dictionaries or arrays passed at them instead of a number (they don't have a toNumber method). In that case, it returns the default value.
function getNumberProperty(key, defaultValue) { var value; try { value = Properties.getValue(key); } catch (e) { value = defaultValue; } return validateNumber(value, defaultValue); } function validateNumber(value, defaultValue) { if (value == null || !(value has :toNumber)) { value = defaultValue; } else if (!(value instanceof Lang.Number)) { try { value = value.toNumber(); } catch (e) { value = defaultValue; } } if (value == null) { value = defaultValue; } return value; }
For boolean, it's a bit different since there is no toBoolean method but Numbers are accepted so this seems to work with all the cases I threw at it
function validateBoolean(value, defaultValue) { if (value == null) { value = defaultValue; } else if ((value instanceof Lang.Boolean) || (value instanceof Lang.Number)) { try { if (value) { value = true; } else { value = false; } } catch (e) { value = defaultValue; } } else { value = defaultValue; } if (value == null) { value = defaultValue; } return value; }
The 'if' inside the 'try' could be an overkill though.