views:

66

answers:

3

I know it is bad convention/design to conditionally declare a variable. i.e.:

if some_boolean:
   x = 1

where x is not declared anywhere else. But is it bad to conditionally declare a variable if you only use it later on if that condition is met?

if some_boolean and some_other_boolean:
   x+=1
+2  A: 

It's dubious style, as it's prone to bugs based on imperfect, impartial understanding on some future maintainer's part. I also think that initially setting variables to None (unless more useful values are known for them) is helpful to readability, in part because it gives you one, natural place to document all of the variables with comments (rather than spreading such comments all over the place, which makes them hard to find;-).

Alex Martelli
+1  A: 

if your code look like this

if some_boolean:
   x = 1
# some actions
# not changing some_boolean
# but calculating some_other_boolean
# ...
if some_boolean and some_other_boolean:
   x+=1

Can it be refactored to

def some_actions(some_args,...):
#...
def calculate_some_other_boolean(some_other_args,...):
#...
if some_boolean:
    x = 1
    some_actions(some_args,...)
    if calculate_some_other_boolean(some_other_args,...):
        x+=1
else:
    some_actions(some_args,...)

?

Odomontois
A: 

From a very simple design perspective, I'd just default the boolean to false even if it maybe won't be used later. That way the boolean in question is not maybe defined or maybe actually a boolean value, and in the event that it is used, it has a proper value.

If you have two or three booleans set to false and they never get used, it's not going to make any significant difference in a big picture sense. If you have more than a few, though, it may indicate a design problem.

banzaimonkey