else 和 return,你喜歡哪種?

2015-04-01 10:50:55 +08:00
 fliar

今天被要求把這段改成else
if(file_exists($fn))
{
//printf("it is a file\n");
$re = $serv->sendfile($fd, $fn);
//printf("Send %s\n", $re ? "Success" : "Failed");
return;
}
$serv->send($fd, $result);
改成
if(file_exists($fn))
{
//printf("it is a file\n");
$re = $serv->sendfile($fd, $fn);
//printf("Send %s\n", $re ? "Success" : "Failed");
}
else
{
$serv->send($fd, $result);
}
請幫忙分析下哪種好,為什麼:)

4828 次点击
所在节点    PHP
28 条回复
xmbaozi
2015-04-01 18:30:42 +08:00
@angelface 赞同
lidashuang
2015-04-01 18:31:50 +08:00
没有return的语言只能用if else了
cxshun
2015-04-01 18:32:04 +08:00
以前喜欢if else,现在喜欢return,没用的代码早点结束,看着舒服多了,而且嵌套层次也可以少点。
ellipse42
2015-04-01 23:57:04 +08:00
raise
Septembers
2015-04-02 03:55:09 +08:00
@Phariel
单出口 大多数情况下会提高代码复杂度
尽可能降低代码复杂度更为重要

完成逻辑尽快退出
执行生命周期过长
不利于GC优化
Septembers
2015-04-02 03:58:58 +08:00
修正 单出口 我是指function内只有一个return
blue7wings
2015-04-02 09:32:20 +08:00
我还是比较倾向于第一个的,但是如果有多个if,我更喜欢用goto语句:
if(file_exists($fn)){
//printf("it is a file\n");
$re = $serv->sendfile($fd, $fn);
//printf("Send %s\n", $re ? "Success" : "Failed");
goto end;
}
if (condition) {
//something error
goto end;
}
$serv->send($fd, $result);

end:
return false;
有点try-catch的意思了...
iyangyuan
2015-04-02 13:09:48 +08:00
虽然单出口是原则,但我还是觉得有时候用return 可以使代码很简洁易读,读者不必读完整个代码段。尤其是在做参数合法性的时候。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/180783

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX