if 或 Else 的结果为正?
这是基于编码风格的,想知道是否最好将 if/else 决策的积极结果放在 if 或 else 块中。例如:
yes_no = object.get() #Response will be 'yes' or 'no'
if yes_no == 'yes':
yes response
else:
no response
优于:
yes_no = object.get() #Response will be 'yes' or 'no'
if yes_no != 'yes':
no response
else:
yes response
据我所知,没有什么区别,因为它们都寻找“是”并输出“是”响应,但是是否有人们遵循或发现更容易阅读的任何样式?
我正在使用 python,但由于 if/else 无处不在,我想其他语言也相关。
编辑:替换通行证没有任何响应,因为没有必要。
This is coding style based, was wondering if it's better to put a positive outcome from an if/else decision in the if or else block. For example is:
yes_no = object.get() #Response will be 'yes' or 'no'
if yes_no == 'yes':
yes response
else:
no response
better than:
yes_no = object.get() #Response will be 'yes' or 'no'
if yes_no != 'yes':
no response
else:
yes response
As far as I can tell there's no difference, as they both look for a 'yes' and output a yes response, but is there any sort of styling that people follow or find easier to read?
I'm using python, but since if/else is everywhere I guess other languages are relevant also.
EDIT: Replaced passes with no response, as were unnecessary.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为这主要取决于程序员想要强调的内容。 IF 条件应该是:
就我个人而言,我总是尽量避免这种情况:
I think that most depends on what the programmer wants to highlight. The IF condition should be either:
Personally I always try to avoid this:
!is_no
)会更干净无论条件是什么,都首先放置早期语句:
!is_no
)Put early out statements first, whatever the condition is:
这严格取决于您的程序的逻辑。如果提出“积极”条件有意义,那么就将其设为积极条件。如果它是一个消极的“条件”,那就让它成为一个消极的条件。对于这两种类型的情况,都没有固定的风格规则,或者至少据我所知没有。
That strictly depends on your program's logic. If it makes sense to make a "positive" condition, then make it a positive condition. If it's a negative "condition", then make it a negative condition. There are no set rules of style when it comes to conditions of either type, or at least not that I am aware of.
我能给你的最好建议是在代码中做最容易读的事情,不要为不添加任何内容的代码路径而烦恼。我会将您的代码修改为:
如果没有针对
no
条件的操作,则没有理由检查它。我还会修改“get”,使其更明显地显示为什么它会返回“是”或“否”响应。实际上,object.get()
相当模糊。Best advice I could give you is do what reads best in your code and don't bother with code paths that don't add anything. I would rework your code as:
If there's no action for the
no
condition there's no reason to check for it. I'd also rework the "get" to make it more obvious why it is returning a yes or no response. As it is,object.get()
is pretty vague.如果您的方法仅返回两个值之一,请让它
返回 True
或返回 False
,而不是任意字符串。您可能应该重命名它,以便方法名称有意义。那么您可以执行
或省略
else
。如果只有一种情况实际上会导致响应,
If your method only returns one of two values, have it
return True
orreturn False
, not arbitrary strings. And you should probably rename it so the method name means something.Then you can do
or
omitting the
else
if only one case actually leads to a response.