I commonly use a boolean condition/variable when it's something too big or complicated and takes too much space by itself inside if
s - basically to avoid repeatability and thus improve readability. E.g. has_three_repeated_digits = len(some_number) == 4 and len(set(some_number[1:]) and set(some_number[:-1])) != 1 and ...
etc. So it is used as if has_three_repeated_digits:...
However, I've noticed it is quite common to use boolean-returning functions instead:
def has_three_repeated_digits(number):
return len(number) == 4 # ... etc
And it is used as if has_three_repeated_digits(some_number): ...
So, when should I turn my boolean variable has_foo
into a function has_foo(bar)
? My initial suspicion is that I should do it whenever this variable will be used inside another method, or at a similar situation (as making a boolean variable global would be quite... ugly?). But I'm not sure.