Home > Enterprise >  how to convert two similar methods in one?
how to convert two similar methods in one?

Time:09-22

How can I make one method generic method doRetry out of these two methods doRetryA and doRetryB in Java where moth boths execute similar code but differs in func1 and func2 calls where func1 and func2 take same number of arguments and these arguments are same types but func1 and func2 differs in functionalities but return same type?

SomeType foo = someEnum.enumValue;


private SomeType def doRetryA() {
    for(int attempt=0; attempt<retries; attempt  ) {
        foo = func1(a, b);
    return foo;
}

private SomeType def doRetryB() {
    for(int attempt=0; attempt<retries; attempt  ) {
        foo = func2(a, b);
    return foo;
}

CodePudding user response:

Define an interface like so:

interface ThrowingBiFunction<A, B, C> {
  C apply(A a, B b) throws IOException, InterruptedException;
}

then accept an instance of this in your method:

private FooType doRetry(ThrowingBiFunction<AType, BType, FooType> func) {
    for(int attempt=0; attempt<retries; attempt  ) {
        foo = func.apply(a, b);
    return foo;
}

I don't know the types of a, b or foo. Perhaps they are the same in both cases, perhaps they're not. If they're not the same, add some type parameters, e.g.

private <AType, BType, FooType> FooType doRetry(ThrowingBiFunction<AType, BType, FooType> func) {

Then invoke:

doRetry((a, b) -> func1(a, b));  // Or doRetry(this::func1) or similar.
doRetry((a, b) -> func2(a, b));

CodePudding user response:

you can pass the function type you want using a string variable as something like this...

SomeType foo = someEnum.enumValue;

private SomeType def doRetry(String funcType) {
    for (int attempt=0; attempt<retries; attempt  ) {
        if (funcType.equals("ONE")) {
            foo = func1(a, b);
        } else if (funcType.equals("TWO")) {
            foo = func2(a, b);
        }
    }
    return foo;
}

//function call
doRetry("ONE");
  • Related