问题
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
?
回答1:
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.
回答2:
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:
- what @assylias and @Holger said about interface vs. realization and chaining ability
- and the fact that
CompletableStage
has a method CompletableFuture<T> toCompletableFuture().
来源:https://stackoverflow.com/questions/34930840/should-i-return-completablefuture-or-future-when-defining-api