Search code examples
javarestweb-servicesjava-8code-duplication

Duplicate Code with different object types


I have to write the code below a few times which violates "DRY" principle (getting a warning in IntelliJ about duplicate code). The only thing that changes is what gets passed into objectMapper.writeValueAsString()

How would I put this in a function that would accept different object Types so I don't violate DRY? I don't know what concept to look up so I apologize if this is a duplicate post. Thanks.

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

Solution

  • Just make it into a method. Be sure that anything passed into the method is in fact serializable.

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