Java equals() selection

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

1 Like

Corresponding tweet for this thread:

Share link for this tweet.

I think that it is important to discuss with your team how the majority feels about this kind of situation and create a guideline for the project.

Anyway, I personally prefer to use Enums instead of this kind of constant.

1 Like

Hi @sona11,
If you are using Java8 (or ablove) you can use Optional - for example:

boolean eq = Optional.ofNullable(aStringVariable)
            .map(s -> s.equals(MY_CONSTANT_STRING))
            .orElse(false);

And when the aStringValue is null there will no NullPointerException

I hope I understood the question correctly, does that help?

1 Like

Thanks you and yes it does help.

1 Like