derrdji
derrdji

Reputation: 13321

Should I return CompletableFuture or Future when defining API?

In Java 8, is it better for interface or abstract class to define APIs returning CompletableFuture instead of returning Future? Considering it is ugly converting Future to CompletableFuture and the fact that CompletableFuture will give the caller more flexibility of using functional style directly, what could be a good reason for an API to just return Future?

Upvotes: 13

Views: 3325

Answers (2)

derrdji
derrdji

Reputation: 13321

Thought I would come back to this and provide some updates on my final decisions:

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

  • this is a protected abstract method of an internal part that I want to make extensible;
  • I do not need an interface to define the binding;
  • the main purpose of this return type is a Future (for async IO), I personally feel the functional-styled API provided by CompletableFuture is an added benefit/reminder/encouragement of using functional style to the future devs.

With that being said, I would definitely use the CompletableStage interface as the return type, had I been designing a public API, because:

Upvotes: 3

assylias
assylias

Reputation: 328608

My 2 cts:

  • by returning a Future, you keep your options open and can return a Future, or a CompletableFuture - it makes no difference from the caller's perspective.
  • by returning a CompletableFuture, you give the caller more options (they get more methods) but you also commit to returning that type of Future - if in two years you realise that returning a BetterFuture would make more sense, you will have to change the API, which is not good.

So you should probably assess the likelihood that you will want to return something other than a CompletableFuture in the future (haha) and decide accordingly.

Upvotes: 2

Related Questions