Home > Back-end >  Merging 2 request classes into a single class with required fields in Java?
Merging 2 request classes into a single class with required fields in Java?

Time:04-28

I have 2 requests as CreateRequest and UpdateRequest. The only difference is that, some fields are not required in the UpdateRequest. For this reason, I need to overload the following method that takes CreateRequest:

private void setRequest(CreateRequest request) {
    IntegrationRequest intRequest = new IntegrationRequest();
    intRequest.setLocationId(request.getLocationId());
    intRequest.setApiToken(request.getApiToken());

    // other setters and procedures
}

The overloaded method is this:

private void setRequest(UpdateRequest request) {
    IntegrationRequest intRequest = new IntegrationRequest();
    intRequest.setLocationId(request.getLocationId());
    intRequest.setApiToken(request.getApiToken());

    // other setters and procedures
}

Both method are called from the same class and for this reason, I cannot pass the requests as a generic way. In this scene, I am wondering if there is a better approach instead of overloading setRequest in order to use a single method instead of 2 methods?

CodePudding user response:

What about using an Interface for both CreateRequest and UpdateRequest?

interface Request {
    String / int getLocationId();
    String getApiToken();
}

class CreateRequest implements Request {
    public CreateRequest(String apiToken) {
        // check for apiToken != null and set the value to your object
    }
    ...
}

class UpdateRequest implements Request {...}

Then you would only need one method setRequest which gets an interface implementation of Request as parameter.

private void setRequest(Request request) {...}

You can also combine it with your base class:

abstract class BaseRequest {
    String / int locationId;
    String apiToken;

    // getter / setter / other stuff
}

The signature of your Request classes then would be:

class CreateRequest extends BaseRequest implements Request {...}

class UpdateRequest extends BaseRequest implements Request {...}
  • Related