我知道有条件地声明一个变量是不好的约定/设计。IE:
if some_boolean:
x = 1
其中 x 未在其他任何地方声明。但是,如果仅在满足该条件后才使用它,那么有条件地声明一个变量是不是很糟糕?
if some_boolean and some_other_boolean:
x+=1
我知道有条件地声明一个变量是不好的约定/设计。IE:
if some_boolean:
x = 1
其中 x 未在其他任何地方声明。但是,如果仅在满足该条件后才使用它,那么有条件地声明一个变量是不是很糟糕?
if some_boolean and some_other_boolean:
x+=1
这是一种可疑的风格,因为基于某些未来维护者的不完美、公正的理解,它很容易出现错误。我还认为,最初将变量设置为None
(除非它们知道更多有用的值)有助于提高可读性,部分原因是它为您提供了一个自然的位置来记录所有带有注释的变量(而不是将此类注释传播到整个地方,这让他们很难找到;-)。
如果你的代码看起来像这样
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
可以重构为
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,...)
?
false
从一个非常简单的设计角度来看,即使以后可能不会使用它,我也会将布尔值默认为。这样,所讨论的布尔值可能没有被定义,或者实际上可能是一个布尔值,并且在使用它的情况下,它具有适当的值。
如果您设置了两个或三个布尔值false
并且它们从未被使用过,那么从全局意义上讲,它不会产生任何显着差异。但是,如果您有多个,则可能表明存在设计问题。