Are Scala Futures Really Functional?

I read this post blog which claims that Futures are not "functional" as they are just wrappers of side effects. For example, they contain RPC calls, HTTP requests, etc. Is it correct?

The blog post gives the following example:

 def twoUsersFeed(a: UserHandle, b: UserHandle) (implicit ec: ExecutionContext): Future[Html] = for { feedA <- usersFeed(a) feedB <- usersFeed(b) } yield feedA ++ feedB 

you lose the desired property: consistent results (the referential transparency). Also you lose the property of making as few requests as possible. It is difficult to use multi-valued requests and have composable code.

I am afraid I do not understand. Could you explain how we will lose consistent result in this case?

+5
source share
1 answer

The blog fails to make a proper distinction between Future and how it is commonly used, IMO. You can write code with pure functional code with Future , if you only ever wrote Future , which called pure, general functions; such code will be referentially transparent and “functional” in every remotely sensible sense of the word.

It is true that Future gives you limited control over side effects if you use them with methods that have side effects. If you create Future wrapping webClient.get , then creating this Future will send an HTTP call. But this is not a fact about Future , but a fact about webClient.get !

There is some truth to this blog. Separating the expression that calculates your calculations, performing it completely, through, for example, the Free Monad, can lead to a more efficient and more verifiable code. For instance. you can create a “query language” where you express an operation, such as “fetching profile photos of all the common friends A and B,” without actually starting. This makes it easier to verify the correctness of your logic (because it’s very easy to make, for example, a test implementation that can “run” the same requests or even just check the “request object” directly), and, as I think, the blog post is trying to suggest , means that you could, for example, combine several queries to get one profile. (It's not even purely functional programming — some OO books have the idea of ​​a “command pattern,” although IME functional programming tools, such as the for / yield syntax, make it a lot easier) If all you have is the fetchProfile method , which immediately starts an HTTP request at startup, then if your code logic requests the same profile twice, there is no way to avoid getting the same profile twice.

But this is not entirely about Future per se, but IMO on this blog, more confusing than useful.

+11
source

Source: https://habr.com/ru/post/1209662/


All Articles