如何避免Java中的方法重载以避免重复?

时间:2018-08-23 07:35:56

标签: java design-patterns coding-style

我有两种方法可以执行80%的相同工作,但结果处理不同。我在做:

 private <T> T getResponse(final RestURI query, final Class<T> responseClass) throws IOException {
        T response = null;

        final RestResponse<Record> tempResponse = getResponseFromDataPath(query);

        if (isResponseOK(tempResponse, query)) {
            final CustomReader reader = createCustomReaderFromResponse(tempResponse);
            response = objectMapper.readValue(reader, responseClass);
                                                          ^
            // DIFFERENCE --------------------------------|
        }

        return response;
    }

    private <T> T getResponse(final RestURI query, final TypeReference valueTypeRef) throws IOException {
        T response = null;

        final RestResponse<Record> tempResponse = getResponseFromDataPath(query);

        if (isResponseOK(tempResponse, query)) {
            final CustomReader reader = createCustomReaderFromResponse(tempResponse);
            response = objectMapper.readValue(reader, valueTypeRef);
                                                          ^
            // DIFFERENCE --------------------------------|
        }

        return response;
    }

这看起来很重复。如何做到这一点,以减少重复。

1 个答案:

答案 0 :(得分:5)

您可以使用调用BiFunction的{​​{1}}参数:

objectMapper

呼叫者可以选择如何呼叫private <T> T getResponse(final RestURI query, final BiFunction<CustomReader, ObjectMapper, T> mapper) throws IOException { T response = null; final RestResponse<Record> tempResponse = getResponseFromDataPath(query); if (isResponseOK(tempResponse, query)) { final CustomReader reader = createCustomReaderFromResponse(tempResponse); response = mapper.apply(reader, objectMapper); } return response; }

objectMapper

或者:

getResponse(query, 
   (reader, objectMapper) -> objectMapper.readValue(reader, <valueTypeRef>);