CodeSOD: Counting Arguments

Lucio C inherited a large WordPress install, complete with the requisite pile of custom plugins to handle all the unique problems that the company had. Problems, of course, that weren't unique at all, and probably didn't need huge custom plugins, but clearly someone liked writing custom plugins.

One of those plugins found a need to broadcast the same method invocation across a whole pile of objects. Since this is PHP, there's no guarantee of any sort of type safety, so they engineered this solution:

function call($name, $args) { if (!is_array($this->objects)) return; foreach ($this->objects as $object) { if (method_exists($object, $name)) { $count = count($args); if ($count == 0) return $object->$name(); elseif ($count == 1) return $object->$name($args[0]); elseif ($count == 2) return $object->$name($args[0], $args[1]); elseif ($count == 3) return $object->$name($args[0], $args[1], $args[2]); elseif ($count == 4) return $object->$name($args[0], $args[1], $args[2], $args[3]); elseif ($count == 5) return $object->$name($args[0], $args[1], $args[2], $args[3], $args[4]); elseif ($count == 6) return $object->$name($args[0], $args[1], $args[2], $args[3], $args[4], $args[5]); } } }

I'll admit, this code itself may not be a WTF, but it points at a giant code smell of over-engineering a solution. It's also fragile code. If two underlying objects have the same name, they must take the same number of arguments, and whoever invokes this must supply than number of arguments. Oh, and nobody can accept more than 6 arguments, which should be all you ever need.

Actually, that last one probably is a good rule. Gigantic parameter lists make your code harder to read and write.

Then again, this method also makes it harder to read and write your code. It's the sort of thing that, if you ever find yourself writing it, you need to go back and re-evaluate some choices, because you probably shouldn't have. But maybe Lucio's predecessor needed to.

"Don't ever do this, until you do, but you still shouldn't have," seems to be a good description of this code.

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published.