开发者

A positive result in if or Else?

开发者 https://www.devze.com 2023-04-04 21:44 出处:网络
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:

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.


I think that most depends on what the programmer wants to highlight. The IF condition should be either:

  • the most probable
  • the simplest
  • the one which leads to less calculation
  • the more readable
  • ...

Personally I always try to avoid this:

if condition:
    ... tons of code ...
else:
    ... one line of code ...


  • Most of the time it's cleaner to avoid double negative (like !is_no)
  • Put early out statements first, whatever the condition is:

    if(!a): 
        return
    else:
        long 
        sequence
        of
        statements
    


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.


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:

yes_no = object.get() #Response will be 'yes' or 'no'
    if yes_no == 'yes':
        yes response

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.


If your method only returns one of two values, have it return True or return False, not arbitrary strings. And you should probably rename it so the method name means something.

Then you can do

if object.get():
    # do something
else:
    # do something else

or

if not object.get():
    # do something
else:
    # do something else

omitting the else if only one case actually leads to a response.

0

精彩评论

暂无评论...
验证码 换一张
取 消