Alex M
Alex M

Reputation: 25

A positive result in if or 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.

Upvotes: 0

Views: 439

Answers (5)

Don
Don

Reputation: 17606

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 ...

Upvotes: 3

kapex
kapex

Reputation: 29959

  • 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
    

Upvotes: 2

Tim Pietzcker
Tim Pietzcker

Reputation: 336148

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.

Upvotes: 0

AlG
AlG

Reputation: 15157

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.

Upvotes: 0

Andy Ibanez
Andy Ibanez

Reputation: 12254

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.

Upvotes: 1

Related Questions