我在几个地方看到过这个,人们使用
if(null == myInstance)
代替
if(myInstance == null)
前者只是风格问题,还是在(我认为更直观)后者之前对性能有任何影响?
我在几个地方看到过这个,人们使用
if(null == myInstance)
代替
if(myInstance == null)
前者只是风格问题,还是在(我认为更直观)后者之前对性能有任何影响?
It depends actually on the language you are using.
In the languages where only bool
type is recognized as a condition inside if
, if (myinstance == null)
is preferred as it reads more naturally.
In the languages where other types can be treated (implicitly casted, etc.) as a condition the form if (null == myinstance)
is usually preferred. Consider, for example, C. In C, int
s and pointers are valid inside if. Additionally, assignment is treated as an expression. So if one mistakenly writes if (myinstance = NULL)
, this won't be detected by the compiler as an error. This is known to be a popular source of bugs, so the less readable but more reliable variant is recommended. Actually, some modern compilers issue a warning in case of assignment inside if
(while
, etc.), but not an error: after all, it's a valid expression in C.
你这样做是为了避免你错误地将值设置为myInstance
to null
。
错字示例:
if (null = myConstant) // no problem here, just won't compile
if (myConstant = null) // not good. Will compile anyway.
通常,出于这个原因,许多开发人员会将等式的常数部分放在首位。
以这种方式编写条件检查也称为Yoda 条件。