Andreas Lazar (2) [Avatar] Offline
#1
Hi All

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

Cheers
Enrico Buonanno (82) [Avatar] Offline
#2
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.
478793 (1) [Avatar] Offline
#3
The honest functions is used to write a code.as a college lecture.this article is very useful for me.i would like to share this informations to my students.thanks a lot for sharing this post.if you looking more about me please visit the website top colleges in india