Parameter Hell

January 11, 2014

With the rise of popularity in Asynchronous JavaScript applications, the phrase _callback hell _has become quite popular.

For more check out:

All of this talk about Callback Hell got me thinking about anti-patterns that I run into when working with synchronous code.

Parameter Hell

If you’ve worked in enough legacy codebases, or maybe even too many modern ones — you’ve probably run into a travesty that looks something like this:

function new_person($species = 'mammal', $race = 'human', $alive = 'yes', $legs = 'two', $name = null);

You get the idea.

If you think that’s ugly, you should see what happens when you need to call a function like that but you only need, let’s say, the fifth parameter to be set. Are you ready?

$new_user = new_person(NULL, NULL, NULL, NULL, 'Jon');

That’s not even the worst of it. It can get way worse if you need, say, exact true‘s and false‘s in order to get the right defaults. Often times you end up with code like this:

some_function(true, true, false, true, false, false, false, $name);

Here’s the thing. None of this is necessary

Setting Some Limits

The first thing you can do to cure Parameter Hell is set a hard limit on the maximum number of parameters allowed in your codebase. I think 3 is a sane limit.

A Simple Solution

The next part, the re-factoring, is really not that bad.

Simply replace all of those individual options with an options array. Something like this:

function newFunction($options) {
    $name = $options['name'];
    $age = $options['age'];

You get the idea. This is just a lot nicer for other programmers to work with later, because they don’t need to keep track of what position in your list of parameters their item is, just set what they need and pass it in.

$options = array(
    'name'      => 'Jon',
    'age'       => 26,
    'privilege' => 'admin'

That wasn’t so bad, was it?