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.


David Linsin 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

Amiga 500 Restoration: A501 Memory Expansion

Something to know about Toshiba external USB HDD