简体   繁体   中英

Best way to refactor methods that have the same code but different return values

I have this piece of code:

public A methodA(X answer) {
  ... 
  return A;
}

public B methodB(X answer) {
  ... 
  return B;
}

So, for example, I have two call those methods in different methods, because the return type is different, so for example, on the controller:

public A version1(X answer) {
 ...
 A ant = methodA();
 ...
}

public Bversion2(X answer) {
 ...
 B bee = methodB();
 ...
}

The point is that every other single line of code is the same, except the calls specified. How can I refactor this code in Java to avoid using duplicated code?

I'd extract the unique part of the code to a Supplier , move the common code to one method, and have the original methods call that underlying method with a supplier:

public A version1(X answer) {
    return unversioned (answer, this::methodA);
}

public B version2(X answer) {
    return unversioned (answer, this::methodB);
}

private <T> T unversioned(X answer, Supplier<T> supplier) {
    // Some code before the supplier
    T result = supplier.get();
    // Some code after the supplier, that may interact with the result
    return result;
}

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