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

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")) { return ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access