📎 AI Summary:
The thread discusses the use of Yoda conditions in Java to avoid null pointer errors when comparing strings, with the original poster questioning if using a constant string on the left side is good practice. The responder explains that Yoda notation is a common and effective coding strategy across languages to prevent assignment errors, emphasizing its role in error handling. Overall, the conversation highlights that using Yoda conditions is considered a good practice for safer string comparisons, though personal preferences may vary.

mishrajicoder

New Member
Member details
Joined
Oct 17, 2022
Messages
6
Thread Author #1
In Java, if I try to do.equals() on a null string, a null pointer error is issued. I’m wondering whether I can perform the following if I’m attempting to compare if a string is equal to a constant string:
Code:
MY CONSTANT STRING.equals(aStringVariable)
I’m sure it’ll work, but is this simply extremely bad code?
This is a common Java idiom known colloquially as a Yoda condition. Personally, I prefer to handle the null situation directly, but the Yoda method is widely used, and any competent Java programmer should quickly grasp what is going on. How should I proceed?
 

Solution
Answering language agnostically, the majority of a program is typically error handling. Yoda notation is typically a best practice. The reason for it is to avoid syntax errors in languages that use == as the equals operator. Yoda notation will throw an error if I do 'success' = variable vs variable = 'success' which will cause an assignment to occur and unexpected code execution

Neemobeer

Windows Forum Team
Staff member
Member details
Joined
Jul 4, 2015
Messages
8,995
Answering language agnostically, the majority of a program is typically error handling. Yoda notation is typically a best practice. The reason for it is to avoid syntax errors in languages that use == as the equals operator. Yoda notation will throw an error if I do 'success' = variable vs variable = 'success' which will cause an assignment to occur and unexpected code execution
 
Solution