Readable Arguments

From Zanecorpwiki

Jump to: navigation, search

Consider this function call:

$total = determine_total('rambling.location l LEFT OUTER JOIN rambling.addressable p ON l.id=p.id', $predicate);

It's not immediately clear what the first argument is for. In this case, a developer familiar with SQL will probably recognize it as a FROM clause, We have to pause a sec to figure it out though. And of course there are often far more enigmatic examples:

if (processGenericRepsone($xml, $status, true) { ... }

WTF is true? One has to go to the function definition (or docs) to figure it out. One solution is to use descriptive constants. This is not always practical or possible. In the first example, the clause is probably going to change with every use. In the second, if the true is replaced with a dynamic predicate clause, then it may be no more clear and the constant trick doesn't work.

Instead, consider naming variables even if they are only used once in arguments to make those arguments more readable:

$from_clause = 'rambling.location l LEFT OUTER JOIN rambling.addressable p ON l.id=p.id';
$total = determine_total($from_clause, $predicate);

and:

var hideNonErrorMessages = true;
if (processGenericRepsone($xml, $status, hideNonErrorMessages { ... }

Now the code is much more literate.

Personal tools