
Rafael Cunha de Almeida wrote:
I don't think that safeSecondElement is worse than secondElement. I think it's better for the program to crash right away when you try to do something that doesn't make sense.
Getting the secondElement of a list with one or less elements doesn't make sense, so you are definetely doing something wrong if you expected the list to have two elements, but it doesn't. It's best that the program crashes there, than propagate the error and crash somewhere else or, worse, not crash at all and give a wrong answer.
There are two different issues at stake here, one is reactive and the other is proactive. You're responding to the reactive question: how do I deal with unexpected errors when they arise? But those who argue against partial functions are usually responding to the proactive question: how do I prevent unexpected errors from arising in the first place? By allowing partial functions we allow for the introduction of unexpected errors, which then forces us to handle the reactive question of what to do when those errors show up. But if partial functions are avoided, then there are no unexpected errors (of that sort) which could ever show up. We already have to deal with bottom, that's a fact of life for general-purpose programming. But partial functions allow us to introduce bottom in new ways. When we have bottom meaning just non-termination, then we have a good idea about how we should treat it. But once we start introducing other bottoms for things like non-exhaustive pattern matching or recoverable exceptions, then it's no longer clear what exactly bottom means. This in turn makes it hard to know whether the semantics of the program match the semantics we want. In particular, I'm a fan of semantics which say my program will not crash. Sure, crashing is better than silently corrupting everything; but not crashing is better than crashing. -- Live well, ~wren