Yoda programming style is a coding convention in which the verb (i.e., the operator) in a conditional statement is placed before the subject. This style gets its name from the Star Wars character Yoda, who speaks with a distinctive reverse syntax (e.g., "When 900 years old you reach, look as good, you will not" instead of "You will not look as good when you reach 900 years old").
Here's an example of Yoda programming style in Java:
if (null == object) {
// do something
}
In this example, the operator "==" is placed before the subject "object", which follows the Yoda style.
One reason for using Yoda programming style is to avoid a type of programming error known as an "assignment mistake." This can happen when a programmer intends to use the "==" operator to compare two values, but accidentally uses the "=" operator, which assigns a value to a variable.
For example, consider the following code snippet:
if (x = y) { // This is an assignment, not a comparison!
// do something
}
This code will always execute the block inside the if statement, because the "=" operator will always assign the value of "y" to "x".
By using Yoda programming style, we can avoid this type of mistake:
if (y == x) { // This is a comparison, as intended
// do something
}
While Yoda programming style can help prevent assignment mistakes, it is generally not considered a best practice in Java. The Java language itself does not enforce a particular coding style, so it is up to individual developers and teams to decide what style they prefer. Some developers find Yoda's programming style to be confusing and hard to read, while others find it helpful in avoiding mistakes. As Uncle Bob also says - “Code that protects the author at the expense of the reader is flawed code.”
In general, it is a good idea to use a consistent coding style within a project and to follow established best practices. If you are working on a team, it is important to agree on a coding style and follow it consistently. This will help to make your code more readable and maintainable.