1

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 :(

1

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to it!!
Sorry, forgot to mention that we aren't working on Java 8 yet
2

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.

3 Comments

Oooo I like this one more than my answer. Well done!
Sorry, forgot to mention that we aren't working on Java 8 yet
Sadly pre Java 8 there is no nice way to handle this (unless leveraging Polymorphism and Inheritance)
1

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));

1 Comment

Sorry, forgot to mention that we aren't working on Java 8 yet
0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.