0

I was working with CompletableFutures when I ran in to situation. Let's say I wanted to do some clean up when an asynchronous operation completed. Is there an important difference between calling a member function in this way? Why would I choose the first example over the second?

Take these two examples:

someAsyncOperation.apply(foo).whenComplete(MyClass::handleOperationCompletion);

Versus:

someAsyncOperation.apply(foo).whenComplete((results, ex) -> handleOperationCompletion(results, ex));

Calling the static function, from an anonymous function, let's me add additional arguments in the local scope. In this second case I could add a local variable:

final Closeable object = new SomeCloseable();
someAsyncOperation.apply(foo).whenComplete((results, ex) -> handleOperationCompletion(results, ex, object));

I feel like this could be useful if I need keep context on some object to perform clean up (e.g like close a stream), and I can still write unit tests for it. Is there a trade off I'm missing here?

Erracity
  • 229
  • 2
  • 13
  • Looks like you're debating between member methods and static methods - what does it have to do with anonymous class ? and yes, static is bad for testing. – Nir Alfasi Mar 20 '17 at 19:36
  • Lambda function = anonymous function = "(results, ex) -> handleOperationCompletion(results, ex, object)" I'm debating between using that pattern or: " MyClass::handleOperationCompletion" Apologies. If this isn't clear I'll try to update the question. – Erracity Mar 20 '17 at 19:55
  • 1
    See duplicate for an answer straight from the horse's mouth. – Kayaman Mar 20 '17 at 20:14
  • Inside `whenComplete` you're calling `handleOperationCompletion` once as a static method and the other option is as a member method. The fact that it's wrapped with lambda is just a technical detail but I don't see how it affects anything. So after all it looks like you're debating between making a method static or not... – Nir Alfasi Mar 20 '17 at 20:46

0 Answers0