I'm smrt'er.
This was sent in by the same anonymous user that submitted the code for I'm smrt. I guess the poor guy is still maintaining what appears to be some nightmare code. At least it gives us something to snicker at as we write our own nightmare code.
The story starts with our anonymous submitter having to dig through the code to figure out why some of the SQL queries were failing. What he found wasn't pretty...
<?php
function sql_val_format($table, $field, $value) {
if($value == "") {
return("NULL");
} elseif((!eregi('^[a-z]*\(.*\)$', $value)) && (!ereg('^0x', $value))) {
return("'".addslashes($value)."'");
} else {
return($value);
}
} // sql_val_format()
function sql_insert($table, $values) { // insert into a table
GLOBAL $SQL;
sql_flush_cache();
$what = $val = false;
while(list($k, $v) = each($values)) {
if($what) {
$what .= ",$k";
$val .= ",".sql_val_format($table, $k, $v);
} else {
$what .= "$k";
$val .= sql_val_format($table, $k, $v);
}
}
....
} // sql_insert()
?>
Check out that sql_val_format()! It takes two arguments which it doesn't use, then checks the value against a regexp to determine if it should be quoted. To top this all off, this quirky abstraction layer is built /on top/ of PEAR::DB. So DB::quote() / DB::quoteSmart() could have been used instead.
Functions that take unnecessary arguments are some of worst WTFs. Imagine sql_val_format()
being used hundreds of times in the code and then you want to change it just to use the $value
argument. You'll have to find it everywhere and make the changes and then extensively test to make sure it didn't break anything. Most of us would probably just deal with the unnecessary requirements and keep using three arguments. This is one of those WTF's that live forever, eternally producing more and more bad code. The best and often the least feasible (money, time, sanity) is to find it everywhere in the code and fix it.
I'm currently re-reading The Pragmatic Programmer: From Journeyman to Master which has a great example of this. Anybody that has ever read it likely remembers the Broken Windows Theory. The Broken Window Theory basically says a single broken window creates the perception of abandonment and soon results in everything going to hell. The same applies to code. You create a broken window like sql_val_format()
and it will cause everybody to start thinking the project is already a waste and they in turn will produce crappy code.