Short note on code readability

Yesterday I came across a piece of code which at first had me a little startled. My first impression was, that the events would not be sent to any listener. Then I thought it would throw a NullPointerException. Only after that I realized that its fully functional, but a little awkward style-wise:

    public static void handle(String data) {
        DataListener dl;
        for (Iterator iterator = dataListeners.iterator(); iterator.hasNext(); dl.eventOccurred(data)) {
            dl = (DataListener)iterator.next();
            System.out.println("Sending data to " + dl.toString());
        }
    }

Did you get it? I have never before seen someone do the "actual work" in the third part of the for loop... Reminded me that even a short piece of code written in an unorthodox style can be somewhat challenging to grasp at first sight.

Comments

david said…
You really got me there! I actually had to think hard about the dl.eventOccured(data) and why it doesn't throw a NPE.

This piece of code shows how important conventions are!
Byju Joy said…
common in old C style programming, where 'for' loop is one of the powerful things available

Popular posts from this blog

SAXParseException: -1:-1: Premature End Of File - Misleading error

Can't start server: Bind on TCP/IP port: No such file or directory

FindBugs - Writing custom detectors (Part 1)