具有不同对象类型的重复代码

时间:2018-08-17 04:58:37

标签: java rest web-services java-8 code-duplication

我必须在下面编写几次违反“ DRY”原理的代码(在IntelliJ中收到有关重复代码的警告)。唯一改变的是传递到objectMapper.writeValueAsString()

的内容

如何将其放入可以接受不同对象类型的函数中,以免违反DRY?我不知道要查找什么概念,因此对这是重复的帖子,我深表歉意。谢谢。

try(CloseableHttpClient client = HttpClients.createDefault()){
    ObjectMapper objectMapper = new ObjectMapper();
    String bodyRequest = objectMapper.writeValueAsString(id);
    StringEntity entity = new StringEntity(bodyRequest, ContentType.APPLICATION_JSON);
    HttpPut request = new HttpPut(url);
    request.setEntity(entity);

    try(CloseableHttpResponse response = client.execute(request)){
        int statusCode = response.getStatusLine().getStatusCode();

        if(statusCode != HttpStatus.SC_OK){
            System.err.println(statusCode + ": " + response.getStatusLine().getReasonPhrase());
        }
    }
}
catch(Exception e){
    throw new RuntimeException(e);
}

1 个答案:

答案 0 :(得分:2)

只需使其成为一种方法即可。确保传递给该方法的所有内容实际上都是可序列化的。

public Object doSomething(Object id) {
    try(CloseableHttpClient client = HttpClients.createDefault()){
        ObjectMapper objectMapper = new ObjectMapper();
        String bodyRequest = objectMapper.writeValueAsString(id);
        StringEntity entity = new StringEntity(bodyRequest, ContentType.APPLICATION_JSON);
        HttpPut request = new HttpPut(url);
        request.setEntity(entity);

        try(CloseableHttpResponse response = client.execute(request)){
            int statusCode = response.getStatusLine().getStatusCode();

            if(statusCode != HttpStatus.SC_OK){
                System.err.println(statusCode + ": " + response.getStatusLine().getReasonPhrase());
            }
        }
    }
    catch(Exception e){
        throw new RuntimeException(e);
    }
}