97 Things Every Programmer Should Know

(Chris Devlin) #1

Collective Wisdom from the Experts 139


if (!time.substring(9, 11).equals("AM") &
!time.substring(9, 11).equals("PM")) {
return false;
}

If none of this series of comparisons failed, returning false, the method
returned true.


If the preceding code seems wordy and difficult to follow, don’t worry. I
thought so, too—which meant I’d found something worth cleaning up. I refac-
tored it and wrote a few unit tests, just to make sure it still worked.


When I finished, I felt pleased with the results. The new version was easy to
read, half the size, and more accurate because the original code tested only the
upper boundary for the hours, minutes, and seconds.


While getting ready for work the next day, an idea popped in my head: why not
validate the string using a regular expression? After a few minutes of typing, I
had a working implementation in just one line of code. Here it is:


public static boolean validateTime(String time) {
return time.matches("(0[1-9]|1[0-2]):[0-5][0-9]:[0-5][0-9] ([AP]M)");
}

The point of this story is not that I eventually replaced over 30 lines of code
with just one. The point is that until I got away from the computer, I thought
my first attempt was the best solution to the problem.


So, the next time you hit a nasty problem, do yourself a favor. Once you really
understand the problem, go do something involving the creative side of your
brain—sketch out the problem, listen to some music, or just take a walk out-
side. Sometimes the best thing you can do to solve a problem is to put the
mouse down and step away from the keyboard.

Free download pdf