VOOZH about

URL: https://www.javacodegeeks.com/2021/10/ground-zero.html

⇱ Ground Zero - Java Code Geeks


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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

👁 Photo of Ashley Frieze
Ashley Frieze
October 24th, 2021Last Updated: October 11th, 2021
0 78 1 minute read

Ashley Frieze

Software developer, stand-up comedian, musician, writer, jolly big cheer-monkey, skeptical thinker, Doctor Who fan, lover of fine sounds
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz