2

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
3
  • 2
    I don't think that this is 'bad' at all. I think that it might be a sign that you should split classes or functions into smaller components but sometimes, thats not feasible. Did you have a particular case in mind? Commented Aug 11, 2010 at 0:37
  • It's just my script allows the user to specify options. It's just depending on the option, my script does different things both at the beginning and the end of the script. Commented Aug 11, 2010 at 0:39
  • I definitely agree that it points to bad modularity in the code. Are you familiar with SRP? Posting a sample of your code might help us point you to how it might be refactored. Commented Aug 11, 2010 at 2:26

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

?

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.