Funny Java Code
25 March 2010 in articles by Regina ten Bruggencate
Some 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?
Duchess is a global network for connecting women in Java technology. Its mission is to promote women in this sector and to provide a platform through which women can connect with each other and get involved in the greater Java community.
I’m not sure if this is as funny in English as it is in Dutch….
private static boolean isPentecoste(Calendar calendar) {
int year = calendar.get(Calendar.YEAR);
Calendar easter = findEaster(year);
easter.add(Calendar.DAY_OF_MONTH, 50);
// easter is now the first day of pentecoste
int dateMonth = calendar.get(Calendar.MONTH);
int dateDay = calendar.get(Calendar.DAY_OF_MONTH);
int pentecosteMonth = easter.get(Calendar.MONTH);
int pentecosteDay = easter.get(Calendar.DAY_OF_MONTH);
return (dateMonth == pentecosteMonth && dateDay == pentecosteDay);
}
In Dutch we have a saying when Easter and Pentecost (Pasen en Pinksteren) are on the same day I will do that or that will happen. Like the English saying when hell freezes over.