|
|
|
|
|
by joelgwebber
4227 days ago
|
|
See my comment above for why I don't find this to be that great for server code. 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. 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 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.