Should I return CompletableFuture or Future when defining an API?

In Java 8, is it better for an interface or abstract class to define APIs that return a CompletableFuture instead of a Future ? Given this ugly conversion of Future to CompletableFuture , and the fact that CompletableFuture will give the caller more flexibility to use the functional style directly, which might be good why the API just returns Future ?

+8
java java-8 interface future completable-future
source share
2 answers

My 2 cts:

  • By returning the Future, you keep your options open and can return the future, or CompletableFuture - this has nothing to do with the perspective of the caller.
  • By returning CompletableFuture, you give the subscriber more options (they get more methods), but you also undertake to return this type of future - if after two years you realize that returning BetterFuture will make more sense, you will have to change the API, which is not very good.

Therefore, you should probably assess the likelihood that you will want to return something other than CompletableFuture (haha) in the future and make an appropriate decision.

+3
source share

I think that I will return to this and give some updates to my final decisions:

For my own code / design, I went using CompletableFuture as the return type, because

  • this is the protected abstract method of the inside that I want to make extensible;
  • I do not need an interface to define a binding;
  • The main goal of this type of return is the future (for async IO), I personally believe that the functional API provided by CompletableFuture is an additional advantage / reminder / encouragement to use the functional style for future developers.

With that being said, I would definitely use the CompletableStage interface as a return type if I were developing a public API because:

+1
source share

All Articles