Complex problems require skilled programmers

4 AM February 8, 2006

Writing maintainable code requires a balancing act between making each line of code simple and keeping each method concise. In my current project, I keep choosing conciseness over apparent simplicity, because I don't think making it look simple would help.

For example, the following function schedules a task for a single user:

private void scheduleTask(final User user) {

    int waitMs = getWaitMs(user);

    timer.schedule(new TimerTask() {

        public void run() {

            new SafeRunnable() {

                protected void runProtected() {





    }, Utils.randInt(waitMs), waitMs);


(Actually, the real code has some comments to explain the implementation a little. The method uses the standard java.util.Timer class to initiate the checks. Since the checkFor() method does a small amount of I/O, a new thread needs to be spawned in order to keep the timer thread responsive. SafeRunnable is our own threading utility class that prevents unexpected runtime exceptions from terminating the underlying thread pool. The random initial wait time ensures that checks for multiple users having the same wait time don't occur all at once.)

I did consider refactoring this method into named inner classes, or even regular classes, because the vast majority of Java programmers throw up their hands and say, "huh?", at the sight of double-nested anonymous classes.

However, it seemed best to put all the code in one place, because it will save jumping back and forth in the editor when reading the code later (during debugging or enhancements). I don't feel the need to make the code more accessible to programmers who aren't comfortable with anonymous inner classes: I suspect that they wouldn't understand the threading issues anyway.

It's a trade-off that makes me feel like I'm being arrogant, but at the end of the day, complex problems require skilled programmers.

By alang | # | Comments (2)
(Posted to javablogs, Java and Rants)


At 08:07, 08 Feb 2006 Niels wrote:

"complex problems require skilled programmers"
And careful documentation.

Remember, the next guy is problably only half as smart as you are.

At 11:13, 08 Feb 2006 AndrewR wrote:

a) Code needs to be clear because in a year's time some person will need to be able to make sense of it in a hurry.
b) "some person" will be you.

Having said that, I don't think the code sample above is too bad.


Add Comment

(Not displayed)

(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)

© 2003-2006 Alan Green