Ground Zero
In some languages, and by some I probably mean JavaScript, values are tested for truthiness. Any value can be treated as a boolean.
This gives us a special case with zero.
Consider this:
if (element.top && element.top < viewport.top) { hidePane(); }
The above is probably ensuring that there’s a value for element.top
and then testing that it’s off screen… but is it really doing that?
By testing this with an element at screen position zero with the viewport starting at 0, we might discover that the logic behaves in an unexpected way.
While it’s important to test things with realistic looking numbers, we can often forget that there’s an important edge case lurking at zero when there’s also falsy as a concept in our programming language. This is as much a test failure as an implementation gotcha.
In a recent bug, I had the following typescript:
if (element?.top && element?.top < viewport.top) { ... }
It looks like a more convincing test for the element
not being null/undefined than the previous test for the top
not being defined… but… when top === 0
then this code === goes wrong
.
The correct implementation should have been:
if (element && element?.top < viewport.top) { ... }
But it was the test case that was most important. We should definitely have remembered to test with the value zero.
Sometimes ZERO === EVERYTHING!
Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: Ground Zero Opinions expressed by Java Code Geeks contributors are their own. |