Reputation: 4094
I've seen this in a few places, people using
if(null == myInstance)
instead of
if(myInstance == null)
Is the former just a matter of style or does it have any performance impact in front of the (more intuitive, in my opinion) latter?
Upvotes: 1
Views: 66
Reputation: 35594
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.
Upvotes: 5
Reputation: 5026
You do that, to avoid that you by mistake set the value of myInstance
to null
.
Example for a typo:
if (null = myConstant) // no problem here, just won't compile
if (myConstant = null) // not good. Will compile anyway.
In general a lot of developers will put the constant part of the equation in first position for that reason.
Writing conditional checks this way is also referred to as Yoda Conditions.
Upvotes: 1