0

I have a a few lines of code which repeat itself in many methods:

public String removeItemsX() {
    MyReq myReq = new MyReq();
    myReq.setName(<String>);
        
    StandardResponse standardResponse = null;
    try {
        standardResponse = A.removeItemX(myReq); // This method call is different, the rest is the same
    } catch (Exception ex) {
        ...
    }
    
    return standardResponse;
}

Now I have many methods

removeItemX();
removeItemY();
removeItemZ();
...

which have almost the same code above, just the method calls are different:

A.removeItemX(myReq);
A.removeItemY(myReq);
A.removeItemZ(myReq);
    ...

Is it possible to define just one method, an pass into somehow only the different method calls?

neblaz
  • 683
  • 10
  • 32
  • 2
    https://stackoverflow.com/questions/4685563/how-to-pass-a-function-as-a-parameter-in-java – NiVeR Jul 05 '21 at 08:19
  • This question is confusing. Perhaps you could rewrite to use a contrived but specific realistic-seeming example. – Basil Bourque Jul 05 '21 at 08:19
  • Can you not change method to `removeItem(int itemCode)`? – AKSingh Jul 05 '21 at 08:20
  • Have a look at function interfaces and lambdas which have been introduced in Java 8. However, even with Java 7 and earlier this would be possible just with a little more code (this basically is the strategy pattern). – Thomas Jul 05 '21 at 08:24
  • Use the following method `String removeItems(Consumer callback) { ... }` and call it like so: `removeItems(A::removeItemX)`. – Seelenvirtuose Jul 05 '21 at 08:25
  • I cannot change anything about the method calls, because it is an API I use, which is coded that way. And I have to use it, that's why I asked the question, to not duplicate code many times. – neblaz Jul 05 '21 at 08:34
  • @Seelenvirtuose: What to do with 'callback" inside the method body? If have to do callback.accept(...); it return void, but I need the StandardResponse from the method passed in. – neblaz Jul 05 '21 at 09:05
  • Ah. Sorry. The use a `Function` instead. – Seelenvirtuose Jul 05 '21 at 12:25

0 Answers0