Should I return CompletableFuture or Future when defining API?

99封情书 提交于 2019-12-05 00:49:41

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.

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!