//Comment This Out

Wednesday, March 30, 2005

Poorly Written Code: Part III

This is another entry in my on-continuing saga of poorly written code. Yesterday, I was working on some code that looped over an Enumeration. An Enumeration, for those non-Java people is not the traditional enumeration (recently introduced in Java 5.0) but a list-like collection that was present in the early days of Java and is kept around for backwards compatibility. Here is how it looped over the Enumeration. if (enumeration != null) { while (enumeration.hasMoreElements()) { if (enumeration != null) { while (enumeration.hasMoreElements()) { // do something } } } } What I ended up doing is converting the Enumeration to an ArrayList (the "favoured" List class) and ended up with the following. if (list != null) { for (Iterator iter = list.iterator(); iter.hasNext(); ) { //do something } }

2 Comments:

  • Shocking code.

    But why are you keeping a list around which might be null? Why not always allocate it and leave it empty?

    BTW: Have you seen my recent post on infinite mutual recursion?

    By Blogger Jason H. Elbaum, at 5:51 a.m.  

  • The Enumeration (now List) was returned by a method which may or may not have returned a null. In truth, the list would have never been null in this case, but it doesn't hurt to check.

    I can think of a case where one would prefer "lazy instantiation". i.e. only create a list object when it is needed. Thus, one may need to check to see if it is null in certain cases. (This wasn't one of those cases, though.)

    By Blogger Avrom, at 6:47 p.m.  

Post a Comment

<< Home