Java equals() selection

For discussions about programming, and for programming questions and advice


Moderator: Forum moderators

Post Reply
KalamyQ
Posts: 16
Joined: Wed Jul 13, 2022 10:59 am
Has thanked: 3 times

Java equals() selection

Post 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?

sfein1000
Posts: 96
Joined: Fri Mar 25, 2022 1:38 am
Been thanked: 4 times

Re: Java equals() selection

Post 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.

Post Reply

Return to “Programming”