A short post is dedicated to all fans of Star Wars and Java / JavaRush in honor of the 40th anniversary of the release of Episode V of the star saga! Sometimes you can find a lot of interesting things on the Internet, and the other day I came across a rather funny at first glance programming practice called Yoda conditions . In short, Yoda conditions (also Yoda notation) are a programming style in which the two parts of the familiar comparison expression in conditional statements are reversed:
nine six parts of the Saga, we, without sleep, sat down to write some code for our pet project and wrote the following:
if (5 == a) {
// do something
}
This style can be used in languages with C-like syntax, most often in expressions with if
and while
.
if (0 == variable) {
// do something
}
while (false == endingCondition) {
// do something
}
Why shift the constant expression to the left side of the comparison operator? Let’s assume a hypothetical situation in which, after a marathon viewing of all void checkNumber(int a)
{
if (a = 13) // Здесь-то и появляется так называемый unexpected behavior!
{
printf("Number is 13");
}
}
In this case, every time you run the program, you will receive the string Number is 13"
, regardless of the argument passed а
to the method checkNumber(int a)
. This is not what we expected! Logical errors can occur quite often among novice programmers (believe me, I KNOW). But at the compilation stage, code like 13 = a will produce an error, which we certainly will not overlook, since the integer value is a constant and, accordingly, cannot change (turn into “a”).
There are both pros and cons to using Yoda's conditions.
Light Side:
-
Preventing assignment to a variable when our goal is comparison.
-
Resolving the problem of unsafe "Null Behavior" (
NullPointerException
) // examples from Wikipedia
Without Yoda:
String myString = null;
if (myString.equals("foobar")) { /* ... */ }
// This causes a NullPointerException in Java
With Yoda:
String myString = null;
if ( "foobar".equals(myString) ) { // Результат - Ложь
/* не выполняется */
}
Dark Side:
- The readability of the code for people who will look at your code becomes more complex, increasing the load on the perception of the code.
- Narrow scope, only comparison for equality or comparison with a constant is used, checking for null.
- Many compilers already “see” errors of this kind and warn in advance about the presence of a potential error.
GO TO FULL VERSION