Simplifying function signatures

Generally speaking, the fewer number of arguments that a function accepts the better, by which I mean the purpose and intended use of a function should be clear, concise, and predictable.

Take for example the following function signature:

function get_status( $id, $returnLabel = false ) {};

The possible return patterns of this function are as follows:

$statusID = get_status( 1 );
$statusLabel = get_status( 1, true );

In the first example usage of the get_status function the purpose and intent is clear: return the status of a given object with an identifier of 1. This could be made even more clear by naming the function get_status_by_id( $id ), but that is a separate point.

In the second example usage of the get_status function the purpose and intent is unclear. It is unclear how the second parameter, a boolean, changes the return value: return the status of a given object with an identifier of 1 and something should be different about it.

Looking at the function signature we see that the second parameter changes the return value to a different property of the object.

Ideally, this should be two functions, get_status() and get_status_label().

If this example is discovered in the wild, then we can refactor a backwards compatible implementation with a wrapper function that maps to the bool arguments. For example:

function get_status( $id, $returnLabel = false ) {};

function get_status_label( $id ) {
    $returnLabel = true;
    return get_status( $id, $returnLabel );
}

The new function is clear in the purpose of the function and does not break existing usage of the original get_status function. From here, usage of get_status can be refactored to use the new get_status_label() function.

Extracting numerous arguments

Sometimes a function requires a large number of arguments and this can seem unavoidable when working with large sets of data. For example, when working with a mailing address, instead of passing each property of the address as an argument we can can pass a single object parameter which represents the address.

Consider the following:

function formatAddress( $street, $city, $state, $zip ) {};

function formatAddress( Address $address ) {};

This reduces numerous arguments, which are expected in a specific order, with a single argument.

Discussing functions based on the number of arguments

A function with a single argument is known as a monadic function, while a function with two arguments is known as a dyadic function. These terms are useful when discussing code and refactoring to simplify function signatures. In the above example, we refactored a dyadic function to a monadic function.

Additionally, a function with no arguments is known as a niladic function, which is even better than a monadic function.

Generally speaking, the fewer number of arguments that a function accepts the better.

By Kyle B. Johnson

Senior Developer @givewp, previously @ninjaforms, @sendwp.