09 April 2012

How Not To Iterate

I can't believe that I am currently devoting serious brainpower into rewriting some code that I got from ${third_party_vendor}.  The code sort-of looks like this:


import java.util.*;

// This class defines an object that, for whatever reason,
// can expired over time.  When this object has expired, 
// it can be removed from the system.
class SomeObjectThatCanExpire 
{
    private boolean expired = false;

    public boolean getExpired() { return expired; }
    public void setExpired(boolean e) { expired = e; }
}

.....

class StupidArrayIterationTest
{
    public static void main(String argv[])
    {
        int i;
        ArrayList al = new ArrayList();

        for (i=0; i<10; i++) {
            al.add(new SomeObjectThatCanExpire());
        }

        ....time passes....

        // remove all expired objects from the system
        // (unfortunately, this code is incorrect)
        for (i=0; i < al.size() ; i++) {
            if (al.get(i).getExpired() == true) {
                al.remove(i);
            }
        }
    }
}

The hilarious thing about the code that I am dealing with is that everything is a bit more complicated than this toy code, and that the original programmer(s) seemed to be dimly aware of the problem here ("gee, why don't all of the expired objects get removed from the "list"?).  But...instead of fixing the problem correctly, they built some crazy scheme in this area of the code to address the problem.

Of course, the "scheme" that was developed in this case is also buggy.  So, my task is to rip out all of this insane code and try to ensure that no crazy side-effects are triggered when the code in this area is actually run correctly.

Who writes code like this?    Arrrrgggghhhhh......

No comments: