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

Duplicate Code with different object types

我必须多次编写下面的代码,这违反了 "DRY" 原则(在 IntelliJ 中收到关于重复代码的警告)。唯一改变的是传递给 objectMapper.writeValueAsString()

的内容

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

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

做成一个方法就好了。确保传递给该方法的任何内容实际上都是可序列化的。

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