Andreas Lazar (2) [Avatar] Offline
Hi All

Just a quick question.
Can a function be honest if it has side-effects?

Enrico Buonanno (85) [Avatar] Offline
That's a really good question, and I'm afraid I can only give an open answer.

Firstly, my idea of an "honest" function is a metaphor to help people write better code; I don't think of it too formally.

The idea is that the signature should express the function's behaviour. So, a function whose signature says that it returns a `String`, but in fact it may return null or throw an exception is "dishonest", because it's "hiding" something. You can make such functions honest by returning `Option<String>`, `Exceptional<String>` etc as appropriate.

Now on to side effects; I think we need to differentiate. I would say that functions that mutate arguments, mutate global state or throw exceptions are dishonest, because their signatures do not acknowledge these effects.

With I/O, things are different. Let's say that any program needs some I/O, and it should be possible to write a program that is entirely honest, so: yes, some side-effecting functions should be considered honest. The solution should be to acknowledge the I/O in the signature. This is done systematically in Haskell, where all impure functions return `IO<T>`.

In C#, most functions that perform I/O return a `Task<T>`, so that the I/O side effect is acknowledged with Task, which you could see as C#'s version of Haskell's IO. Although, to be precise, `Task<T>` may also represent a computationally intensive operation that has no side effects, and there are many side-effecting operations that don't return a Task, such as `Console.WriteLine` or `DateTime.Now`.

You could choose to wrap such synchronous impure operations in a Task-returning functions (translating from implicit to explicit, analogous to what I do with `Exceptional` in Ch6), or in some other wrapper that captures the idea of I/O. This will result in more explicit code, but also more type noise. Whether or not the tradeoff is worthwhile is open to debate and probably depends on the specific program you're writing.