Article NDP5 CodeSOD: Sorting Cabinets

CodeSOD: Sorting Cabinets

by
Remy Porter
from The Daily WTF on (#NDP5)

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 Idiota might try and implement their own sorting algorithm from scratch, but your Regular Idiota just has to call .sort- it's Idiot Proofa, 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.

release50.png[Advertisement] Release!is a light card game about software and the people who make it. Play with 2-5 people, or up to 10 with two copies - only $9.95 shipped! TheDailyWtf?d=yIl2AUoC8zA1yu4MU5YdkQ
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments