简体   繁体   中英

Nested condition vs. return on unexpected result

Consider the two following coding-styles:

Nested conditions:

if(is_numeric($user_id)) {

    // .. do stuff
    if(is_valid_user($user_id)) {
        return foo($user_id);
    } else {
        return FALSE;
    }

} else {
    return FALSE;
}

vs. just simply stopping when something is wrong:

if(!is_numeric($user_id)) {
    return FALSE;
}    

// .. do stuff

if(!is_valid_user($user_id)) {
    return FALSE;
}

return foo($user_id);

This is of course at least partially about taste; but what are these two different styles called?

When are one prefered over the other?

Are there other, perhaps cleaner, coding styles?

You could leave off the else s entirely.

if (is_numeric($user_id)) {

    // do stuff

    if (is_valid_user($user_id))    
        return foo($user_id);
}

return false;

A bit cleaner, less code, still easy to read/understand.

Another coding style related to your question is only having one return statement per method/function.

Schools often teach this principle. I think that Martin Fowler was a proponent of this originally based on some online searches.

The major reason is probably irrelevant to PHP, but in C for example, if you had dynamically allocated memory in the function that needs to be cleaned up, having returns all over the place either leads to repeated code, leaked memory, or having to use goto to get to the code for freeing memory.

I generally go by the idea that the least nesting the easier something is to read. I prefer the second style for that reason. Of course it doesn't matter what style you use, I would even change your second example slightly to make things even easier for me to read.

if(!is_numeric($user_id)) return FALSE;

// .. do stuff

if(!is_valid_user($user_id)) return FALSE;

return foo($user_id);

To me having the return statements on the right makes them stand out. Also, having the whole thing on one line helps me picture the statements being gates and easily spilts the code into sections ... but that is just me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM