In Java, ask if a variable STILL equals null after a possible change in value

225 views Asked by At

In Java, this works:

String foo = a();
if(foo == null){
    foo = b();
}
if(foo != null){
   list1.add(foo);
}

However, its ugly to look at because it looks like it should be handled as an if/else, even though it cannot be. Is there a neat way to handle checking if a variable is STILL null after possibly setting it to a non-null value?

2

There are 2 answers

0
Jazzwave06 On

You have two options:

1) Optional class

// if a() returns an Optional<String>
String foo = a().orElse(b());
if (foo != null) list1.add(foo);

2) Chain of Responsibility pattern for fallbacks

// With a better interface name.
interface Fallback {
    // With a better method name.
    String get();
}

List<Fallback> fallbacks = new ArrayList<>() {{ }}; // add all fallbacks
for (Fallback fallback : fallbacks) {
    String foo = fallback.get();
    if (foo != null) {
        list1.add(foo);
        break;
    }
}
0
Xirema On

If foo is ever assigned a value which "could be null", and if your program will have a problem if foo is ever null, then yes, you need to check after every individual assignment. There's no pattern which will fix this.

One thing you might consider, if the issue is code clutter, is wrapping the first several lines into a function.

String getFoo() {
    String _a = a();
    if(_a != null) return _a;
    else return b();
}

/*...*/

foo = getFoo();
if(foo != null)
    list1.add(foo);

Alternately, you could write a custom Container (or a wrapper around whatever type list1 is) that will gracefully handle the case where it's passed a null instead of whatever object it is expecting.