javaconstructorinput-parameters

How to pass the various input parameters to a method in a class efficiently?


Below is my Interface -

public interface IClient {
    public String executeSync(ClientInput input);
}

This is my Implementation of the Interface -

public class TestingClient implements IClient {

    @Override
    public String executeSync(ClientInput input) {

    }
}

Now I have a factory which gets the instance of TestingClient like this -

IClient client = TestingClientFactory.getInstance();

Now customer is going to make a call to executeSync method of my TestingClient which accepts the ClientInput parameter and below is the class for the ClientInput.

public final class ClientInput {

    private Long userid;
    private Long clientid;
    private Long timeout = 20L;
    private boolean debug;
    private Map<String, String> parameterMap;

    public ClientInput(Long userid, Long clientid, Map<String, String> parameterMap, Long timeout, boolean debug) {
        this.userid = userid;
        this.clientid = clientid;
        this.parameterMap = parameterMap;
        this.timeout = timeout;
        this.debug = debug;
    }

 ... //getters here
}    

So when customer make a call to executeSync method of our TestingClient, they will create the ClientInput parameter like this and then use the factory to get the Instance of TestingClient and then call the executeSync method accordingly.

Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("attribute", "segmentation");

ClientInput input = new ClientInput(109739281L, 20L, paramMap, 1000L, true);

IClient client = TestingClientFactory.getInstance();
client.executeSync(input);

Problem Statement:-

  1. Is this the right way to make ClientInput parameters and pass to executeSync method as shown above?
  2. There are already three arguments of the Long type in my ClientInput it may not be clear to other developers which position is for which field (especially during those long nights...). Any thoughts how to avoid this?
  3. If more inputs are required, it will make the constructor declaration longer. How can I overcome this situation?

Solution

  • Use builder pattern if you have more parameters. That makes code clean. (See this example)

    For instance, you can have

    clientinput.userid("userid)
               .clientid("clientid")
    

    Some parameters if not specified can be optional. Like if timeout and debug are not set, they can take default values