以前は「 anObject != null 」のようにJavaコードのテスト文を書いていましたが、逆に「 null != anObject 」のように書いている人もいました。では、それらの違いは何ですか?Javaでどちらがより良い方法ですか?
4 に答える
Their reasoning is that if you accidentally forget the !
, then you have an assignment instead of a comparison, which cannot happen the second way.
anObject = null
assigns null to anObject
, while null = anObject
will produce a compiler error.
これは、ヨーダの条件に多少関連しています。
"the force".equals(myString);
myString が null の場合、null ポインターを回避します。
It's a style of how people compare expressions.
Do not use null != anObject
as null
is a constant and is considered a Yoda condition.
Always put the variable left hand side and the constant on the right.
From a compiled code point of view there is no difference.
However from a paranoid-programmer point of view it can prevent you from making the dreaded assignment bug.
e.g. if you mistype:
null = myObject
you get a compiler error because you cannot assign to constant.
However if you mistype:
myObject = null
the compiler will not complain. And you may release code that assigns null to your Object instead of testing for null.