Sorting. It’s a well-studied class of problem, with a number of well-understood solutions. These days, pretty much any time you need to sort a collection, there’s a language-or-framework-provided function that handles it for you. Sure, a Better Idiot™ might try and implement their own sorting algorithm from scratch, but your Regular
Idiot™ just has to call .sort
- it’s Idiot Proof™, right
Well, David S. found a better idiot.
public List<CabinetAjax> getAllCabinets() {
try {
List m = new Vector<CabinetAjax>();
List cabinets = SpecificObjectManager.getAllPrograms();
Iterator it = cabinets.iterator();
while (it.hasNext()) {
CabinetAjax ca = new CabinetAjax();
SearchProgramShell cabinet = (SearchProgramShell) it.next();
ca.setId(cabinet.getCabinetId());
ca.setTitle(cabinet.getCabinetTitle());
Collections.sort(m, new CabinetAjaxTitleComparator());
m.add(ca);
}
return m;
} catch (Exception e) {
log.error(e.toString(), e);
} finally {
HibernateSessionFactory.closeSession();
}
return null;
}
The goal here is to return sorted list of Cabinet
details- which you’ll note is just an ID and Title, meaning this could just be a map instead of a class, but that’s barely a WTF. No, it’s the call to sort
every time. According to David, there are 12,000 Cabinet objects, so that’s 12,000 sorts, with one more element each time. I leave the total Big-O for this implementation up to the reader.
Even better- that call to sort
happens before the object is added to the collection, which means the list returned will always be sorted except for the last element in the list.
So not only is it inefficient, but it doesn’t actually work. Oh, and that exception handler is one step up from an empty catch block, and a small step at that.