|
|
|
|
|
by Dewie
4223 days ago
|
|
> If each of those getOrElse() is an actual potential runtime failure (as opposed to just something that could in theory be nil, but you know won't be, by construction), then it's something you're going to need to deal with explicitly. getOrElse is a function that is used for exactly that, i.e. for things which can fail in the sense that a parser failed to parse some text because there was a syntax error in the string, or the Map datastructure didn't contain the given key so it returns "nil" or "None" or whatever. If you had something that you know wasn't supposed to be able to fail, then you would probably just go ahead and assume that it can't fail, and let the program error out if it does fail since then you've revealed a bug. To use getOrElse for things that shouldn't fail to begin with is not good. I don't know what you mean by "deal with it explicitly", since getOrElse indeed does deal with it explicitly. > E.g., think of each of those method calls as being a call to some external system (filesystem, memcache, database, etc) that might fail, even if the code's correct. Throwing an exception is usually a pretty bad strategy for those cases if you want to able to sort out what went wrong later. getOrElse doesn't throw an exception. It returns "null" or "None" or whatever value is supposed to represent "does not exist" in the case of some failure (failure here being "produced none/nil/null"). It has nothing to do with throwing (or catching) exceptions. |
|
For runtime errors, as I've stated above, I prefer explicit handling close to the error site. I think this is the right tradeoff for server code, though I'm less certain for client code.
For validation errors, I prefer, when possible, to have a parser that either succeeds or fails as a whole, and whose output I can then rely upon to be properly constructed.
For unexpected nils, I do like the option-type/monad approach, though in most cases (e.g., when writing Go, Java, C++, or Javascript) I just let them NPE/segfault.
Note that only one of these cases -- runtime errors -- results in a (result, err) pair in Go. The other two are just about result checking.