Article 82FP CodeSOD: One In a Million

CodeSOD: One In a Million

by
Remy Porter
from The Daily WTF on (#82FP)

Marcus inherited a big-ol-ball-of-mud PHP application. The entire thing is one difficult to summarize pile of WTF, but he searched long and hard to find one snippet that actually summarizes how awful the code is.

That snippet is this:

function generate_confirmation_number(){ //compact the job number to two digits by adding digits 1+2 and appending to the sum of digits 3+4 $c_jobno = ($jobno{0}+$jobno{1}).($jobno{2}+$jobno{3}); //generate an array with 1 million elements $numbers = range(0,999999); //get all the confirmation numbers that have been used $rs = $this->_conn->execute("SELECT used_num FROM used_num WHERE used_num LIKE '%s' ORDER BY used_num ASC",$jobno.'%'); if ($rs->get_record_count() > 0) { while (!$rs->eof) { //delete elements in array corresponding to the last six digits of the confirmation number unset($numbers[substr($rs->value('used_num'),4)]); $rs->move_next(); } } //randomize the order of the remaining numbers shuffle($numbers); //glue the compacted job number to the first element in the numbers array (which is ordered randomly) return $jobno.$numbers[0];}

The goal here is to find a number that hasn't been used for a previous "confirmation". To find that, they generate an array with every number from 0 to 999,999, and then query the database for previously used confirmation numbers. They then look at every previously used number, and then try to delete it from the array, if it exists.

inedo50.png[Advertisement] BuildMaster is more than just an automation tool: it brings together the people, process, and practices that allow teams to deliver software rapidly, reliably, and responsibly. And it's incredibly easy to get started; download now and use the built-in tutorials and wizards to get your builds and/or deploys automated! TheDailyWtf?d=yIl2AUoC8zALxVLdOlP65M
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