Use Result Variable to Prepare Function Return Value

Many many years ago I learned Delphi language. It has one interesting feature not found in other languages: you don’t need return statement to specify return value for a function. Instead, you can use a pseudo-variable called Result. You can change its value many times during function execution but only the last value is returned.

That’s really a great idea! Even if your programming language doesn’t have such a built-in variable, why not to create it?
Most functions actually need a variable to forge future return value, so why call it differently if we can always call it result?

For example, this tiny function extracts clean text from HTML fragment:

function GetTextFromHTML($HTML) {
    $result = strip_tags($HTML, '<br>');
    $result = preg_replace('/<BR\b.*?>/isu', ' ', $result);
    $result = str_replace('&nbsp;', ' ', $result);
    $result = HTMLDecode($result);
    $result = trim(preg_replace('/\s\s+/u', ' ', $result));

    return $result;
}

As you can see, it uses $result variable to prepare return value and returns it in the last line. This greatly improves code readability as result name always refers to a variable, which value will be returned at the end of the function.

Using this code style you’ll always have this command in the last line of a function/method:

return $result;

This also improves ability to debug a function as you can simply set a breakpoint at the last line to see the return value.
For example this function decodes HTML encoded text:

function HTMLDecode($Text)
{
    return html_entity_decode($Text, ENT_QUOTES, 'UTF-8');
}

But how we can check the return value in the debugger or log it for debug purposes?
Let’s modify the function code to have result value saved to a variable before returning it:

function HTMLDecode($Text)
{
    $result = html_entity_decode($Text, ENT_QUOTES, 'UTF-8');

    return $result; //Set a breakpoint here
}

Now you can easily check the value of $result variable in the debugger. You can also insert logging code before return statement to log the result value.

You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

Leave a Reply