Before switching to Guava, I found myself writing the function below for every project worked on. It's probably already been implemented in a library, somewhere.
<T> public static T coalesce(T... elements){
for(T element : elements) {
if (element != null) return element;
}
throw new NoSuchElementException();
}
// Usage:
function1(coalesce(function2(param1,param2), "default value"));
It's nice because there's no duplication of code, and you don't have to choose between introducing a temporary variable or performing the same call twice (like the conditional operator thingie previously suggested). It's not nice because, well, it doesn't read very fluently.
If you're using Guava (which you should be), you can use Optional
to avoid null
, which also has the benefit of making your API much clearer and less prone to NullPointerException
s.
void function1(String arg) {}
Optional<String> function2(){ /* insert code*/ }
// Usage:
function1(function2().or("default value"));