SIDEBAR
»
S
I
D
E
B
A
R
«
Use Result Variable to Prepare Function Return Value
December 29th, 2009 by Anton Oliinyk

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', "\n", $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 to see the result
}

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.


Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

SIDEBAR
»
S
I
D
E
B
A
R
«

Valid XHTML 1.0 Transitional