1

我在几个地方看到过这个,人们使用

if(null == myInstance)

代替

if(myInstance == null)

前者只是风格问题,还是在(我认为更直观)后者之前对性能有任何影响?

4

2 回答 2

5

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

于 2013-06-20T11:53:44.123 回答
1

你这样做是为了避免你错误地将值设置为myInstanceto null

错字示例:

if (null = myConstant) // no problem here, just won't compile


if (myConstant = null) // not good. Will compile anyway.

通常,出于这个原因,许多开发人员会将等式的常数部分放在首位。

以这种方式编写条件检查也称为Yoda 条件

于 2013-06-20T11:50:16.240 回答