if by "the string is null-checked", you mean in both cases you have a null check, i prefer 1. it seems more natural to me, probably because that's how i first saw it years ago.
having said that, the whole point of #2 is you don't NEED to do the null check. So if it's a question of 1 with a null check, or 2 without it, then #2.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Hey, we forgot to throw out a "welcome to the ranch!" Welcome aboard!
I see this all the time:
and it makes my little discomfort alarms go off. I prefer
And more than that, I prefer knowing that s cannot be null. When I'm comfortable with that the more conventional s.equals("hello") reads better for most folks.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
It depends. If I'm interested in whether s is null or whether it's equal to the string literal, then I'd go for a seperate null check and the literal on the right. If I don't care if s is null, all I'm interested in is whether it equals the literal, then string literal on the right. On a purely personal note, I prefer the literal on the right but that's just habit.
Personally, I'm more in favor of variable.equals("literal"), because it seems more logical to me when I read it.
The intent is rarely to see if two strings are the same, but rather, to see if the variable holds some specific significant value (if that makes sense to any of you). To do that, we check to see if they are the same.
But to me, when I see "literal".equals(value), I think to myself, why am I checking the value of "literal". I know its value. My intention is to check the value of variable. So I prefer to see variable to the left, because it reads as 'if variable is equal to "literal"', which is what I want.
Having said that, "literal".equals(value) means we don't have to null check. Some people think this is a good thing. Personally, I'd rather see the null check, because it tells me that it is possible that this variable is null. If I don't see the null check, I don't know if there's a possibility that the variable is null.