is it a bad practice to map a suspended effect with an impure function?

85 Views Asked by At

Assuming getData() returns an IO[_] and has all its side effects suspended, I fail to see any difference between

getData().map(d => println(d.toString))

and

getData().flatMap(d => IO(println(d.toString)))

Am I missing something? are both results impure? are both pure? should I avoid the shorter, more readable .map() version for any particular reason?

I think the two are equivalent and both have suspended side effects, so my preference goes to the first one.

1

There are 1 best solutions below

1
Luis Miguel Mejía Suárez On

Both are wrong actually, you should use getData().flatMap(IO.println) :)

Pedantic answers outside, while you are technically correct that the map one would behave exactly the same in isolation (and in the happy path). It is a good idea to get used to the mental model of composing programs rather than mixing pure and impure code because that will lead to a bug sooner rather than later.
Note that doing map(println) is kind of common when doing quick debugs that should not reach production; although for this use case, one should prefer the debug method.

Finally, the reason to prefer IO.println over IO(println) is that printing is blocking, even if short compared to other blocking operations. And this helper manages that for us in the proper way.


BTW, if getData does not need parameters, it shouldn't have an empty parameter list, it could even be a val.