-1

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?

  • Well, an OOP approach would be to implement a fallback pattern. Try every implementations of the fallback until one gives you a valid result. You could also check the `Optional<>` class (https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html). – Jazzwave06 Dec 14 '16 at 22:20
  • Or if you can use Groovy, `String foo = a() ?: b()`. – chrylis -cautiouslyoptimistic- Dec 14 '16 at 22:34
  • if you want to avoid one if condition String foo = (a()!=null ) ? a(): b(); if(foo != null){ list1.add(foo); } – Kiran Kumar Dec 14 '16 at 22:41

2 Answers2

2

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;
    }
}
Jazzwave06
  • 1,883
  • 1
  • 11
  • 19
0

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.

Xirema
  • 19,889
  • 4
  • 32
  • 68