Drew said:
Because it's not almost certaintly wrong. Often null String variables
are expected and perfectly valid.
<sigh> That's not the issue. Of course reference variables can often
be null. The issue is how often you find yourself with two very
specific cases in the logic of your code, those being:
1. String reference is null, or points to a non-empty String.
2. String reference points to an empty String.
[Of course, the literal could be other than the empty String, but I'm
going to assume for the purpose of this discussion that it's the empty
String, because that seems the most likely in a class of unlikely
scenarios.]
And furthermore, the question is whether this situation is enough of the
norm that it's worth recommending a language usage that encodes this as
a general preference, in the way that you did. The problem that this
solves is, in fact, so unique that I'd probably avoid a concise-looking
expression that doesn't deal with the odd intricacies of the desired
logic, and instead write the statement as:
if ((myString == null) || !myString.equals(""))
{
// CASE 1
}
else
{
// CASE 2
}
If you very frequently run into this specific situation, where a null
reference should be treated the same as a non-empty String, but
differently from an empty String, I'm really curious about where it pops
up so frequently. In the mean time, I'm concerned that recommendations
for the "literal".equals(variable) style will be picked up by those who
aren't thinking about the possibility of a null reference, and they will
write code that produces more logic errors and fewer clear and helpful
runtime errors. Those who are already thinking about null references
and considering them as possible inputs are probably competent enough to
express their logic on their own.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation