Many returns

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

stukov
Forum Commoner
Posts: 26
Joined: Sun Jul 24, 2005 2:16 pm
Location: Sherbrooke, Qc, Canada

Many returns

Post by stukov »

I always have been told to have only one return per function while coding. I see many people using plenty of them in their functions, so I am wondering if it is really bad.

Any opinions?
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

If returning early is a "special case","base case", etc. I'd say do it. It will reduce the depth of the nesting, which helps readable code and its easy to see where the special cases finish. If its more complicated, then no.

Ie, if you can write code like

Code: Select all

function foo($bar) (
  if (0==$foo) return 1;
  if (1==$foo) return 2;
  // big nasty rest of logic
  return $calcValue;
}
then I think the multiple returns are good.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

It's the same as saying that goto, break, continue etc are evil.. They are only evil if you don't know (well enough) what they do :P

http://en.wikipedia.org/wiki/Structured_programming
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

In case you see the term, somewhere else, the multi-return method, with most of them being simple returns at the start of the function are often called "Guard Clauses".
stukov
Forum Commoner
Posts: 26
Joined: Sun Jul 24, 2005 2:16 pm
Location: Sherbrooke, Qc, Canada

Post by stukov »

Now it's seems clearer, but over 100 000 visits / minute, will there be a difference at the execution time and at the ressource usage or is it only a way to make code easier to read?
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

There might be a slighlt difference in execution time, but its most likely so far down in the "noise" that I wouldn't worry about it until I've profiled the application under normal/high load.
stukov
Forum Commoner
Posts: 26
Joined: Sun Jul 24, 2005 2:16 pm
Location: Sherbrooke, Qc, Canada

Post by stukov »

Ok. I understand. Thanks a lot.
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

It's not something I ever think about. Just keep functions nice and tight, doing one thing only, and then return as many times as you need in order to do that one thing.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

Only having 1 return statement is a practice, I think, to correct for human error. For myself at least, if there's only 1 return statement, I'm more likely to make sure that 1 statement returns exactly what I want. In other words, I'm sure I've taken care of every condition. If I have return statements all over, then its harder for me to look through the code and be sure I've thought of everything.

It's kind of like having having a default case in a switch statement to make sure everything's handled, as opposed to just having specific cases and trying to be comprehensive with all my cases.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

Well, if your functions are that complicated, maybe you should stick them in a class or something.
stukov
Forum Commoner
Posts: 26
Joined: Sun Jul 24, 2005 2:16 pm
Location: Sherbrooke, Qc, Canada

Post by stukov »

I think I'll stick to

one return per function;
if the use of many returns is required -> the function is not simple enough -> redesign;
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

I don't think you can sustain that.

I grabbed the following two methods at random. In the first, I'm hunting through a list of query types looking for a match. As soon as I find one, I return some information about the query ($meta). There's no need to continue with the loop. If I don't find a match, the fn returns false.

In the second, I'm checking for database.table dot syntax in an sql query. Whatever the query string, I want an array with database and table values out of the function. However, if it's badly-formed (multiple dots) I need to return false since it's effectively unparsable.

Even with nice, short methods, you will need multiple return values at times. It could be a smell but not necessarily so.

Code: Select all

/*
        param (string)
        return (mixed)
    */
    function parse($sql, $currently_used_db)
    {
        $this->_currently_used_db = $currently_used_db;
        foreach($this->_recognised_queries as $query) {
            if(preg_match($query['pattern'], $sql, $matches)) {
                if(count($meta = call_user_func_array(array(&$this, $query['fn']), array($matches)))) {
                    $meta['query_type'] = $query['type'];
                    return $meta;
                }
            }
        }
        return false;
    }
    // $parts[0] db name
    // $parts[1] table name
    function _dotSyntax($query_target)
    {
        $parts = explode('.', $query_target);
        if(count($parts) == 1) {
            array_unshift($parts, $this->_currently_used_db);
        } elseif(count($parts) > 2) {
            trigger_error('unparsable: multiple dots');
            return false;
        }
        return $parts;
    }
Last edited by McGruff on Fri Aug 05, 2005 9:31 pm, edited 2 times in total.
User avatar
harrisonad
Forum Contributor
Posts: 288
Joined: Fri Oct 15, 2004 4:58 am
Location: Philippines
Contact:

Post by harrisonad »

Unexpected errors caused me to return early.

Code: Select all

function ValidEmail($email){
    if(!$email) return false;
    // rest of the code, including the last return statement
}
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

harrisonad wrote:Unexpected errors caused me to return early.

Code: Select all

function ValidEmail($email){
    if(!$email) return false;
    // rest of the code, including the last return statement
}
Exactly (or maybe throw an exception in PHP5)

otherwise you end up with extra nested code
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Post by Ambush Commander »

PHP5 exceptions are really really cool (I read about them). Too bad they aren't in PHP4.
Post Reply