简体   繁体   English

嵌套条件与意外结果的返回

[英]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. 你可以完全抛弃else

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. 与您的问题相关的另一种编码风格是每个方法/函数只有一个return语句。

Schools often teach this principle. 学校经常教这个原则。 I think that Martin Fowler was a proponent of this originally based on some online searches. 我认为Martin Fowler是最初基于一些在线搜索的支持者。

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. 主要原因可能与PHP无关,但在C语言中,例如,如果你在需要清理的函数中动态分配了内存,那么在整个地方返回会导致重复的代码,泄漏的内存或者不得不使用goto获取内存的代码。

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. 此外,将整个事情放在一行上可以帮助我将这些语句描绘成门,并轻松地将代码转换为部分......但这只是我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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