Skip to content
Advertisement

How to avoid having multiple methods with different arguments for url construction

How to avoid having multiple methods with different arguments for url construction. I would like to optimize this further

protected String invUrl() {
    return endpointUrl("invs", null, null);
}   

protected String invUrl(String id) {
    return endpointUrl("invs", id, null);
}   

protected String invUrl(String id, String action) {
    return endpointUrl("invs", id, action);
}   

protected String endpointUrl(String entity, String id, String action) {

    if (id != null && action != null) {
        return UriComponentsBuilder.newInstance().scheme("http").host("localhost").port(serverPort)
            .path("/mat/api/v1/" + entity + "/" + id + "/" + action).build().toUriString();
    } else if (id != null) {
        return UriComponentsBuilder.newInstance().scheme("http").host("localhost").port(serverPort)
            .path("/mat/api/v1/" + entity + "/" + id).build().toUriString();
    } else {
        return UriComponentsBuilder.newInstance().scheme("http").host("localhost").port(serverPort)
            .path("/mat/api/v1/" + entity).build().toUriString();
    }   
}

Advertisement

Answer

One way to create an object called Endpoint which holds the required values:

public class Endpoint {
    private String entity;
    private String id;
    private String action;

    public Endpoint(String entity, String id, String action) {
        this.entity = entity;
        this.id = id;
        this.action = action;
    }

    // getters, toString etc.
}

Then you can have only one invUrl method to which id and action can be passed and Endpoint object can be constructed. This can be passed to endpointUrl method:

protected String invUrl(String id, String action) {
        return endpointUrl(new Endpoint("invs", id, action));
    }

Then, endpointUrl method can be modified as:

protected String endpointUrl(Endpoint endpoint) {
        StringBuilder pathBuilder = new StringBuilder("/mat/api/v1/").append(endpoint.getEntity());
        if(endpoint.getId() != null) {
            pathBuilder.append("/").append(endpoint.getId());
        }
        if(endpoint.getAction() != null) {
            pathBuilder.append("/").append(endpoint.getAction());
        }
        return UriComponentsBuilder.newInstance().scheme("http").host("localhost").port(serverPort)
                .path(pathBuilder.toString()).build().toUriString();
    }

Advertisement