简体   繁体   中英

Java Null Conditional

I have the following pattern appearing many times in my Java code and was wondering how some of you might refactor it.

Object obj1 = buildObj1();
if (obj1 != null) {
    return obj1;
}

Object obj2 = buildObj2();
if (obj2 != null) {
    return obj2;
}

Object obj3 = buildObj3();
if (obj3 != null) {
    return obj3;
}

Because Java doesn't have first-class functions, the best you could really do would be to have an interface for "building things", and then do something like this:

for (Builder<T> builder : builders) {
    T obj = builder.build();
    if (obj != null) return obj;
}

The Builder interface would just be something like:

public interface Builder<T> {
    T build();
}

builders in the top snippet is an Iterable<Builder<T>> .

Is that code all called sequentially in the same method? You could use a Factory method that would always return the correct object (either obj1, obj2, or obj3). You could pull the "null or real object" conditional test from each buildObj() method into this factory method so that you always get a valid object from the new factory method.


Alternatively, if you just mean that you have the if (obj != null) tests everywhere you might instead consider using the Null Object Pattern:

Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), one uses an object which implements the expected interface, but whose method body is empty. The advantage of this approach over a working default implementation is that a Null Object is very predictable and has no side effects: it does nothing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM