if(object == null)与if(null == object)的区别是什么?哪种更优?
What's the Difference Between
if(object == null) and if(null == object)? Which is Better? Ah, this is such a classic interview question—let me break it down clearly for you:
Core Functional Equivalence
First off, from a pure logic standpoint, these two checks do exactly the same thing: they verify whether the object variable references a null value. When your program runs, there’s zero difference in how these two conditions behave.
The Key (and Only Practical) Difference: Preventing Accidental Assignment Bugs
The real distinction comes down to protecting yourself from a super common typo: mixing up the equality operator (==) with the assignment operator (=). Here’s how it plays out:
- If you write
if(object = null)(accidentally using=instead of==), this is a valid statement in most C-like languages (Java, C++, etc.). It assignsnulltoobject, then evaluates the result of that assignment (which isnull, treated asfalsein a boolean context). This will silently break your program’s logic, and in some cases, compilers won’t even flag it as an error—making it a tricky bug to track down. - If you write
if(null = object)(same typo, reversed order), the compiler will throw an immediate error. Why? Becausenullis a constant value—you can’t assign a value to a constant. This forces you to catch the typo right away, before your code even runs.
Which is Better?
This boils down to style and context:
- Many veteran developers (especially those with C/C++ backgrounds) swear by the
if(null == object)style, often called a "Yoda condition" (since it mimics Yoda’s backwards speech pattern like "Do or do not, there is no try"). It’s a defensive coding habit to avoid that assignment typo. - That said, modern IDEs and compilers now frequently warn about suspicious assignments in conditional checks. Some languages (like C# with certain code analysis rules) even block this kind of pattern entirely. So the urgency of using Yoda conditions has decreased a bit. But if you’re working in an environment without robust tooling, it’s still a smart defensive move.
内容的提问来源于stack exchange,提问作者v0ld3m0rt
相关产品推荐
相关产品推荐

