简体   繁体   中英

avoiding code duplication in a java method

Apologies if this has already been asked/answered a thousand times (I did check first).

I'm not a Java programmer by trade and have been tasked with extending an existing Java SOAP service. I'm keen to avoid copy/pasting existing code that I know works, but was wondering what the best options available in java are.

Essentially I have this method already:

public String methodThatIDontWantToCopyPaste(
        @WebParam(name = "a", partName = "a") String paramA,
        @WebParam(name = "b", partName = "b") int paramB,
        @WebParam(name = "c", partName = "c") int paramC) {

    // Validate parameters
    if (paramA.isEmpty() || 
            0 == paramB || 
            0 == paramC) {
        return "Invalid request";
    }
    String response = "";

    try {

        // Parmaeters OK, build client
        /*
        lots of generic implementation here
        ...
        XYZ client = ...
        ...
        */

        response = client.specificMethodToHandleABC(paramA, paramB, paramC);

    } catch (SOAPException | IOException ex) {
       // handling omitted

    } 

    return response;
}

I want to add several new/similar methods, but each will have:

  1. A different set of parameters
  2. A different block of code to validate the parameters (the above code is trivial, but some will be more detailed
  3. A different implementation of the line: response = client.specificMethodToHandleABC(a, b, c); ie where a different method will be called, with a different set of arguments

I'd normally go for a callback in my usual programming language, but it's a proprietary language and not as powerful as Java, so I wanted to know what the best option was?

In a similar setting, I used callbacks/anonymous classes by calling a method out of every endpoint and passing a callback for every variable part into the method, like the following

public String methodA(final int param1, final String param2) throws Exception {
    return this.call(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return param1 != 0 && param2 != null;
        }
    });
}


public String methodB(final String param1, final String param2) throws Exception {
    return this.call(new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return param1 != null && param2 != null;
        }
    });
}

private String call(Callable<Boolean> validationCallable) throws Exception {
    // static code similar to all methods

    assert validationCallable.call().equals(Boolean.TRUE);

    // static code similar to all methods

    return ""; // probably result based on another callable
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM