U
Ulrich Eckhardt
Greetings!
I guess many of you have already seen code (especially from C++ programmers)
like the following:
String s = someFunction();
if(s == "0")
doThis();
else
doThat();
I wonder, is there a way to catch such comparisons where a non-fundamental
type is compared to a constant? I'm actually looking for a way to avoid
errors that occur due to this, maybe a warning when a comparison is done
for identity where one of the two sides required boxing (Is that the term?)
first.
Further, I wonder about this case:
Integer n = otherFunction();
if(n == 42)
dontPanic();
Other than the above, I haven't actually tried it, but I would expect this
code to also not do what a naive programmer would expect.
Just for the record, in case you didn't spot the problem in above code, this
is how the above should be written:
if(s.equals("0")) ...
if(n.equals(42)) ...
// Note: I'm not sure about the latter.
The reason is that '==' determines identity for objects while it determines
equality for builtin types like 'int' (please correct me if I'm wrong or if
this explanation is misleading in any way).
thanks
Uli
I guess many of you have already seen code (especially from C++ programmers)
like the following:
String s = someFunction();
if(s == "0")
doThis();
else
doThat();
I wonder, is there a way to catch such comparisons where a non-fundamental
type is compared to a constant? I'm actually looking for a way to avoid
errors that occur due to this, maybe a warning when a comparison is done
for identity where one of the two sides required boxing (Is that the term?)
first.
Further, I wonder about this case:
Integer n = otherFunction();
if(n == 42)
dontPanic();
Other than the above, I haven't actually tried it, but I would expect this
code to also not do what a naive programmer would expect.
Just for the record, in case you didn't spot the problem in above code, this
is how the above should be written:
if(s.equals("0")) ...
if(n.equals(42)) ...
// Note: I'm not sure about the latter.
The reason is that '==' determines identity for objects while it determines
equality for builtin types like 'int' (please correct me if I'm wrong or if
this explanation is misleading in any way).
thanks
Uli