你们更偏向那种形式?

2014-11-20 10:19:03 +08:00
 66450146
https://gist.github.com/LeeroyDing/9fb16913fc7aa306ad1e
5188 次点击
所在节点    程序员
35 条回复
xidianlz
2014-11-20 15:03:15 +08:00
@Sylv something = 0时候
something和something is not None不都是True么?
regmach
2014-11-20 15:14:26 +08:00
我喜欢第二种
Sylv
2014-11-20 16:36:48 +08:00
@xidianlz 你试试 something = 0 和 something = '' 的情况就知道了
yetone
2014-11-20 18:42:04 +08:00
第二种学名是防御式编程,推荐的写法。
mulog
2014-11-20 21:08:11 +08:00
@xidianlz
显然不是。。。
a = 0
if a:
print a
什么也不会print
hustlzp
2014-11-20 21:13:25 +08:00
个人第二种
cvrock
2014-11-20 21:45:37 +08:00
显然是要分情况的,第一种情况可能会导致if嵌套太深,第二种情况可能会导致每个if内都有一个返回的出口,需要根据具体场景决定选择哪种写法。
fish748
2014-11-21 01:29:11 +08:00
现在用第二种,嵌套少一层。
lightening
2014-11-21 03:56:35 +08:00
if some_condition
do_something
end

def do_something
big_block_of_code
end
dreampuf
2014-11-21 04:13:14 +08:00
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)
dingyaguang117
2014-11-21 09:42:50 +08:00
第二种
whalegia
2014-11-22 04:31:33 +08:00
这种这么细节的知识你们是在哪里看的啊……orz
我不看到这种讨论贴就根本不知道
jox
2014-11-22 09:39:57 +08:00
我尽量不在选择分支里进行这种判断,选择分支里的值只有两个,逻辑真或逻辑假,如果在某个对象的值不存在的时候会使用函数或者提前计算得到布尔值,然后再进行判断。类似这样的:

if isItExist(object):
-- ...
else:
-- ...

函数isItExist()的返回类型是布尔值
66450146
2014-11-22 10:09:20 +08:00
@jox 如果是对数值进行合法性验证呢?
jox
2014-11-22 10:41:19 +08:00
@66450146 合法就是逻辑真,否则就是逻辑假呗

if isValid(object):
-- ....
else:
-- ....

我觉得限制选择分支里的类型为布尔类型,尽量少用0或者void来代替逻辑假,用0或者void(None)之类的代替逻辑假会导致逻辑混乱

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

https://tanronggui.xyz/t/147931

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

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

© 2021 V2EX