Chapter 69. Put the Mouse Down and Step Away from the Keyboard

Burk Hufnagel

image with no caption

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 represents 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 character offset and upper limit, to test the minutes and seconds. The method ended with these lines to check for AM and PM:

if (!time.substring(9, 11).equals("AM") & !time.substring(9, 11).equals("PM")) ...

Get 97 Things Every Programmer Should Know now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.