简体   繁体   中英

Extract generic Function for two different classes in java

I have this switch statement that has the exact same function code repeated twice and I would like to DRY it up:

case "form" -> handleProvider.withHandle(handle -> handle.attach(FormDao.class).findFormById(id))
        .thenApply(form -> { // Form.class
            if (form == null) throw exceptionIfNotFound;
            return form;
        })
        .thenApply(obj -> obj.exportedDocument);
case "note" -> handleProvider.withHandle(handle -> handle.attach(NoteDao.class).findNoteById(id))
        .thenApply(note -> { // Note.class
            if (note == null) throw exceptionIfNotFound;
            return note;
        })

If IntelliJ extract the common bits I get

            final Function<Form,Form> formFormFunction = form -> {
                if (form == null) throw exceptionIfNotFound;
                return form;
            };

which obviously just works for one code path; the Form objects, but not the Note objects. The two objects do not actually implement the same interface here, but on the other hand, I do not make use of any specific interface in the code. I just want to say I have a method that takes a and outputs a unchanged, and that T could be anything.

Make this into a method rather than a variable. This way you can make it generic.

private static <T> Function<T, T> getNullCheckFunction() {
    return t -> {
        if (form == null) throw exceptionIfNotFound;
        return t;
    };
}

Then you can do:

case "form" -> handleProvider.withHandle(handle -> handle.attach(FormDao.class).findFormById(id))
        .thenApply(getNullCheckFunction()) // here!
        .thenApply(obj -> obj.exportedDocument);
case "note" -> handleProvider.withHandle(handle -> handle.attach(NoteDao.class).findNoteById(id))
        .thenApply(getNullCheckFunction()) // here!

Note that what you are doing in the function returned by getNullCheckFunction is very similar to Objects.requireNonNull . If you are fine with throwing NullPointerException instead of your own exception, you can just do:

.thenApply(Objects::requireNonNull)

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