Funny Java Code
March 25, 2010Some funny and not so funny code I found in code reviews.
Example 1:
String detail = getFaultDetail(ctx);
String fault = getFault(ctx);
log.debug("Fault: " + fault);
log.debug("Detail: " + detail);
log.debug("String value: " + String.valueOf(fault));
log.debug("String value2: " + String.valueOf(null));
Result:
Fault: null
Detail: null
String value: null
NullpointerException
Example 2:
String s = readReply(-1L, 500L);
if (s == null)
return null;
else if (advancedMode)
return s;
else
return s;
I think this is a clear case of not refactoring correctly or overthinking all your options a simple return of readReply(-1L,500L) would have been enough.
Example 3:
switch (intValue) {
default:throw new UnknownValueException(intValue);
case 0: case 1: case 2: doSomething(); break;
case 4: doSomething2();
case 3: doSomething3(); break;
}
This is very badcode. When the intValue is 4 both methods doSomething2 and doSomething3 are executed.
The question for a reviewer is do we want this or did someone forget a break after doSomething2();
When a unit test is also missing and specifications are hard to find updating this code is only
for the brave
Example 4:
String test="1234";
boolean contains = false;
if (test.indexOf(3) >= 0) {
contains = true;
}
System.out.println("Result: " + contains)';
The question is what will be the line printed and why?
