97 Things Every Programmer Should Know

(Chris Devlin) #1

(^138) 97 Things Every Programmer Should Know


Put the Mouse Down


and Step Away


from the Keyboard


Burk Hufnagel


YOU’VE BEEN FOCUSED FOR HOURS on some gnarly problem, and there’s
no solution in sight. So you get up to stretch your legs or to hit the vending
machines and, on the way back, the answer suddenly becomes obvious.


Does this scenario sound familiar? Ever wonder why it happens? The trick is
that while you’re coding, the logical part of your brain is active and the creative
side is shut out. It can’t present anything to you until the logical side takes a
break.


Here’s a real-life example: I was cleaning up some legacy code and ran into an
“interesting” method. It was designed to verify that a string contained a valid
time using the format hh:mm:ss xx, where hh represents the hour, mm repre-
sents minutes, ss represents seconds, and xx is either AM or PM.


The method used the following code to convert two characters (representing
the hour) into a number, and verify it was within the proper range:


try {
Integer.parseInt(time.substring(0, 2));
} catch (Exception x) {
return false;
}
if (Integer.parseInt(time.substring(0, 2)) > 12) {
return false;
}

The same code appeared twice more, with appropriate changes to the charac-
ter offset and upper limit, to test the minutes and seconds. The method ended
with these lines to check for AM and PM:

Free download pdf