Page 1 of 1

Java equals() selection

Posted: Wed Nov 09, 2022 1:01 pm
by KalamyQ

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: Select all

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?


Re: Java equals() selection

Posted: Wed Nov 09, 2022 1:16 pm
by sfein1000

Yes you can write constant.equals(variable). As to whether or not you should, that's a question that has people on both sides and you will get approvals and criticisms from both.
The benefit: You don't have to test for null. Code will work as expected (the variable is not equal to the constant)

The detriment: You may run into issues later in code using that same variable. Where, instead, you could test for null earlier and handle the issue appropriately. You will also lose a little readability in that many programmers are not used to the Yoda Method and will be confused by the switch and potentially modify existing code to match how they see things variable.equals(constant) and all of a sudden, working code fails.

In my opinion, I prefer to handle potential issues as opposed to hiding them to make shorter code.