Thursday, September 04, 2008

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);
            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.