Validity
Numbers
Various kinds of math operations can produce ‘NaN’ (Not a Number) or infinity. For example dividing by zero or something which is not a number.
It happens more often than one thinks, if you’re trying to do some math operation on a variable which you think ought to contain a number, but in fact has something else. Using Typescript or using type hinting can help a lot to catch these kinds of bugs.
If any other operation is applied to infinity or NaN, the value is always infinity or NaN. What can happen then is a ‘bad’ value quickly spreads through the execution ‘infecting’ other parts. This makes it hard to track down.
That’s why it’s necessary to do some ‘guarding’ and check the validity of values at key points.
You can use in-built Javascript functions to check for these kinds of numbers:
As you can see, writing defensive functions can add a lot of clutter. For your own code you may not need to worry too much about it, since you’re the only one calling your own functions. But for libraries like ixfx it is useful to have checks on incoming values. In the above example, we aren’t even checking the parameter a
, that’d add even more lines of code!
Since you don’t want to repeat yourself, you could use the same function ixfx uses internally: Guards.throwNumberTest to do the checking. It generates a useful error message and it can also enforce certain ranges of values.
Type checking
Check the type of a variable with typeof
:
In action, compare the result of typeof
with the name of a type:
Does an object contain a field?
Check if an object has a field using in
. In the example below, we print one message if the object has the field humidity
, another one if it doesn’t.
As a side point, a cleaner way to write this would be using a ternary: