Thursday, June 29, 2023

Horror Code: For Each Remove

 This article was posted originally on JRoller on September 13, 2011.

I found this new interesting pattern to loop over all elements of a list in our production code:

    try {
        for (Object element = myList.remove(0); ; element = myList.remove(0)) {
            ...
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        // It's ok
    }

For those who are thinking right now about using it: PLEASE DON'T!

At the time I wrote this article, I had enough faith to believe that people who will read it will understand how much of a bad code it is. In case my faith was wrongly placed, here are two important rules:

1. Do not modify your list while looping. Here, the side effect is that you will end up with an empty list.

2. Do not use an exception for normal code branching. In spite of the comment, it is not ok.

No comments:

Post a Comment