简体   繁体   中英

Concise Java Code: assignment, null check and conditional execution

The following Java code appears to be fairly lengthy and somewhat repetitive. Can it be made more concise?

A myObjA = getObject(id, A.class);

if (myObjA != null) {
  handleA(myObjA);
}

B myObjB = getObject(id, B.class);

if (myObjB != null) {
  handleB(myObjB);
}

C myObjC = getObject(id, C.class);

if (myObjC != null) {
  handleC(myObjC);
}

Forgot to mention. This is not running on Java 8 :(

Sure, thanks to the magic of java-8! Simply create this helper method:

private <T> static void getAndHandleIfNonNull(int id, Class<T> clazz, Consumer<T> handler) {
    T t = getObject(id, clazz);
    if (t != null) {
        handler.accept(t);
    }
}

And then call it:

getAndHandleIfNonNull(id, A.class, this::handleA);
getAndHandleIfNonNull(id, B.class, this::handleB);
getAndHandleIfNonNull(id, C.class, this::handleC);

Refining the other answers:

Optional.ofNullable(getObject(id, A.class)).ifPresent(this::handleA);
Optional.ofNullable(getObject(id, B.class)).ifPresent(this::handleB);
Optional.ofNullable(getObject(id, C.class)).ifPresent(this::handleC);

This is shorter and more concise.

How about making use of the new Java 8 features?

Optional.ofNullable(getObject(id,A.class)).ifPresent(myObjA -> handleA(myObjA));
Optional.ofNullable(getObject(id,B.class)).ifPresent(myObjB -> handleB(myObjB));
Optional.ofNullable(getObject(id,C.class)).ifPresent(myObjC -> handleC(myObjC));

Well, if you can put a null check fence in your handleX methods, your code becomes much more concise.

handleA(getObject(id, A.class));
handleB(getObject(id, B.class));
handleC(getObject(id, C.class));

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