Should using .unwrap() be considered bad practice?

Viewed 415

Seeing the comments under this question, made me wonder - should using unwrap() be considered bad practice?

In my view, sometimes unwrapping makes sense. At least in these two scenarios:

  1. We know an Option value cannot be None, because we have already handled that case, earlier in the code. An example:
if o.is_none() {
    // do some stuff here...
    return ...;
}
// ...
o.unwrap()   //  <--- Here I do NOT expect a None
  1. If we develop a simple short-lived tool, which is simply gonna end on error either way, relying on panics instead of "proper" error handling (with Result, ?, etc.) could simplify code, more or less.

Obviously, sometimes relying on unwrap() might cause more harm than good, so it isn't quite obvious to me whether I should always refrain from using unwrap() or not? If not, when would it be OK to use unwrap()?

1 Answers

We know an Option value cannot be None, because we have already checked that case, earlier in the code. An example:

if o.is_none() {
    return ...;
}
// ...
o.unwrap()   //  <--- Here I do NOT expect a None

While there are cases where this is unavoidable, the "correct" way to handle this is to use pattern-matching e.g.

let o = if let Some(o) = o {
    o
} else {
    return o;
}

or something along those lines.

There are cases where "unwrapping" is unnecessary, but in that case in production software I would use expect with a non-generic explanation, or an explicit panic! with a documentation of the assumption.

If we develop a simple short-lived tool, which is simply gonna end on error either way, relying on panics instead of "proper" error handling (with Result, ?, etc.) could simplify code, more or less.

That wouldn't make it "good practice", that would just make it "I don't care about bad practices in that context".

It's a perfectly justifiable position, but it's not good practices.

Related