I have doubts…
On the first hand, I would definitely go without the ?. I agree with some other posts that the question mark removes readability.
My argument is that question marks in all the spoken languages that I know of are reserved for the start or end of a phrase. Even the ternary operator can be understood as “question ? answer : answer”.
With the let? construct, it is not at all clear what the question is.
let Ok(user) = await ....
let Ok(banana) = user.find("banana")
Cost
My main worry is more about the real usefulness of this pattern with regards to the cost it adds:
- Reduced readability (alternative part of the type matching is hidden)
- Forces the use of (Ok/Error) (or some common type) instead of better variants
- Pushes error handling out where a continuation/retry and other patterns would make more sense
- Adds a new decision while writing code “Should I use the unwrap ?” or when defining types “Should I define my types as Ok/Error to support unwrap ?”
This is a very high cost to reduce code indentation.
What is wrong with this code ?
let veryComplicatedService = (id) => {
let user = switch fetchUser(id) {
| Ok(user) => user
| err => throw MySystemException("some context")
}
// Code never reached on error, no deep nesting.
// Can have an explicit try/catch to return "Error"
}
I would reserve this kind of magic for a language extension, not as a “good practice”.