Hacker News new | past | comments | ask | show | jobs | submit login

> if(obj == null && obj.isValid())

Why would you encounter this (often)? It seems to me that this code would never evaluate to true.




This is Java code. If you test for a null reference AND THEN dereference it, you get a NullPointerException. The check was supposed to be "!= null".

This check is obviously erroneous, and found via SCA. I was saying "if I had a dollar for every time I found this [via SCA] I'd have a lot of money."


I'm curious as well, I understand the bug / typo, but I don't think I've seen it more than a handful in 20+ years of C-like languages (mostly game development). In contrast, typing a single '=' instead of '==' seems a more common error IME (although still not frequent enough to drive me towards Yoda conditions to catch it).

Why do you think you are encountering this particular mistake so often? Is it something about your projects, your organization, your colleagues, or Java itself?


It's a braino, I think. Instead of the right thing, which would be what mathgladiator posted below, this is a guaranteed null pointer exception when obj actually is null.


I hope he means

> if (obj != null && obj.isValid()) { }

Which is semantically correct due to the fail-fast evaluate of AND, it does require a double check since it's strange from a logic point of view. This is one the reasons that brace languages are hard to optimize since you can't commute things that ought to commute.


That statement can't be commuted because it expresses a concept that can't be commuted.

If the two checks were independent (pure functions), it's not difficult for a compiler to determine that given enough program visibility.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: