(null != Somevariable) Or (somevariable != Null)
Solution 1:
They're equivalent.
However, the first one will cause an invalid assignment error if you mistype !=
as =
. Some people like this as it's rather easy to type =
instead of ==
, although the former isn't always an accident.
You can see the precise rules of the specification with regard to the ==
operator on the Annotated ES5.
Solution 2:
They evaluate to the same thing, but it is preferable to choose (someVariable != null)
, because the other way is a Yoda condition. It deals with readability.
Solution 3:
Consider you want this :
if (number == 42) { /* ... */ }
// This checks if "number" is equal to 42// The if-condition is true only if "number" is equal to 42
Now, imagine you forget there should be a double =
and you just write a single =
instead :
if (number = 42) { /* ... */ }
// This assigns 42 to "number"// The if-condition is always true
Such errors are pretty common and can be hard to detect in programming languages that allow variable assignments within conditionals.
Now, consider reversing the order of your condition :
if (42 == number) { /* ... */ }
// This checks if "number" is equal to 42// The if-condition is true only if "number" is equal to 42
The behavior of 42 == number
is exactly the same as the behavior of number == 42
.
However, if make the same mistake mentioned hereabove (you forget there should be a double =
and you just write a single =
instead), the behavior is no longer the same :
if (42 = number) { /* ... */ }
// This produces an error
Therefore, some people prefer to reverse the order of their conditions, as it makes a common error much easier to detect. Such "reversed" conditions are known as Yoda conditions.
In programming languages that do not allow variable assignments within conditionals (eg. Python or Swift), there is no advantage whatsover to using Yoda conditions, and it's typically discouraged to use them. In other languages (eg. JavaScript or PHP), Yoda conditions can be very useful. However, in the end, it's still largely a matter of your personal preference or whatever coding standards your project require.
Wordpress & Symfony are two popular open source projects where Yoda conditions are part of the coding standards.
Post a Comment for "(null != Somevariable) Or (somevariable != Null)"