|
21gramsNov 20, 2014
1
一般来说第二种,可读性更好
|
|
yjsslabNov 20, 2014
2
尽量不在if里使用否定吧,也就是尽量不用unless
|
|
vulgurNov 20, 2014
3
我是第一种,不过不写“is not None”,就是“if something”
|
|
4
分清主次
big_block_of_code()是程序的主干 something is None 之后是分支,次要的 应该把次要的分支写在if里 |
|
jimwooNov 20, 2014
5
- -!什么东西??看不懂!!我只看到了标题!
|
|
rwxNov 20, 2014
8
个人来说第二种
习惯把异常或者错误情况排除之后再写主逻辑,尽可能减少if嵌套 |
|
Ge4LosNov 20, 2014
11
我用第二种, 优先跳出异常或错误, 然后执行主要代码;
主要代码的缩进会靠前, 更容易阅读 |
|
ytll21Nov 20, 2014
12
说看不见的看这个
# First style if something is not None: # or whatever condition big_block_of_code() # Second style if something is None: # or whatever condition continue # or return None or whatever big_block_of_code() |
|
xidianlzNov 20, 2014
14
if something is not None:
为啥不用 if something: 这样不是更pythonic一点? |
|
ozkingNov 20, 2014
16
第二个
|
|
ozkingNov 20, 2014
17
相对来说少缩进一层,
|
|
imn1Nov 20, 2014
18
貌似这两个逻辑不同
单一条件不会有太大区别,只是可读性的问题,如果多条件,可以考虑以下短路方式减少判断 |
|
rebornixNov 20, 2014
19
如果代码比较复杂,我觉得通过fast return来减少内嵌层级比较好。倾向第二种。
|
|
clinoNov 20, 2014
20
@faceair 我用chinadns一样不行阿
2014-11-20 14:51:10 INFO request gist.github.com 2014-11-20 14:51:10 INFO response gist.github.com: [('203.161.230.171', 1, 1)] |
|
regmachNov 20, 2014
22
我喜欢第二种
|
|
yetoneNov 20, 2014
24
第二种学名是防御式编程,推荐的写法。
|
|
hustlzpNov 20, 2014
26
个人第二种
|
|
cvrockNov 20, 2014
27
显然是要分情况的,第一种情况可能会导致if嵌套太深,第二种情况可能会导致每个if内都有一个返回的出口,需要根据具体场景决定选择哪种写法。
|
|
fish748Nov 21, 2014
28
现在用第二种,嵌套少一层。
|
|
lighteningNov 21, 2014
29
if some_condition
do_something end def do_something big_block_of_code end |
|
dreampufNov 21, 2014
30
TLTR: “等于”比“不等于”更符合直觉,避免嵌套优先执行异常分支。选第二种。
via. Code Complete 2nd Summary of Techniques for Reducing Deep Nesting The following is a list of the techniques you can use to reduce deep nesting, along with references to the sections in this book that discuss the techniques: - Retest part of the condition (this section) - Convert to if-then-elses (this section) - Convert to a case statement (this section) - Factor deeply nested code into its own routine (this section) - Use objects and polymorphic dispatch (this section) - Rewrite the code to use a status variable (in Section 17.3) - Use guard clauses to exit a routine and make the nominal path through the code clearer (in Section 17.1) - Use exceptions (Section 8.4) - Redesign deeply nested code entirely (this section) |
|
dingyaguang117Nov 21, 2014
31
第二种
|
|
whalegiaNov 22, 2014
32
这种这么细节的知识你们是在哪里看的啊……orz
我不看到这种讨论贴就根本不知道 |
|
joxNov 22, 2014
33
我尽量不在选择分支里进行这种判断,选择分支里的值只有两个,逻辑真或逻辑假,如果在某个对象的值不存在的时候会使用函数或者提前计算得到布尔值,然后再进行判断。类似这样的:
if isItExist(object): -- ... else: -- ... 函数isItExist()的返回类型是布尔值 |