It is generally agreed that overloading a method should not change its behavior, but how much of a method’s behavior should be kept consistent?
Take for example a REST API client which is responsible for interacting with two different endpoints. Both consume a POST request, share the same base URL, and accept the same headers. The only difference is the payload (and of course the endpoints themselves). If one were to strictly follow the aforementioned rule of encapsulating a single behavior under the same method name, a client similar to the one below may be created:
public class RestClient { private final String API_A = "http://api.somecompany.com/a"; private final String API_B = "http://api.somecompany.com/b"; RestTemplate restTemplate; public ResponseA postA(RequestA request) { HttpHeaders headers = getHeaders(); HttpEntity<RequestA> request = new HttpEntity<>(request, headers); return postForObject(API_A, request, ResponseA.class); } public ResponseB postB(RequestB request) { HttpHeaders headers = getHeaders(); HttpEntity<RequestB> request = new HttpEntity<>(request, headers); return postForObject(API_B, request, ResponseB.class); } private HttpHeaders getHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); return headers; } }
This seems alright but also a little silly because of how similar the methods are. Why not use the same name and just change the request and response type? Will this not imply the endpoint being called? should there be a separate client for each endpoint?