I’ve come to learn that sometimes IntelliJ code inspections can be pretty smart. Even smarter than me, at times. However, often its communication skills are a bit out of whack.
Recently I was working with a code snippet that looked like the following:
addVariable(USER_COUNTRY_KEY, user.countryCode); // ... some other lines of code ... String isLoggedIn = (user == null) ? "no" : "yes";
Now granted this was swimming in a forest of other lines of code and so it was
much less obvious at the time, but the Android Studio code linter was
user == null, telling me that this expression will always
I kept thinking to myself, how would they know that? I kept running through
scenarios in my head over and over, focusing only on that one single line until
it finally dawned on me. Android Studio isn’t telling me that it’s impossible
for my user object to be null, it’s just inferring that since I’m checking for
null on line 2 when I’m already using
user.countryCode on line 1. Obviously if
I NPE on line 1, I won’t make it to line 2.
So the moral of the story is: never simply ignore the code inspections, but on the other hand it’s always important to understand how to fix them and what the implications are, so don’t go blindly fixing things to remove that ugly linter highlighting right away; do your research and make sure you know what’s going on.