Then...and_then ergonomics and readability

I often find myself writing something akin to the following:

(boolean_value)
  .then(||())
  .and_then(|_| produces_an_option())

I know I could just write:

if boolean_value {
  produces_an_option()
} else {
  None
}

...but for various circumstantial reasons, that if statement often leaves me feeling that the code has grown harder to follow. This is particularly true of longer functions: I tend to forget what the outer return type is midway through writing the inner logic, even after I refactor, simplify, or otherwise break things up!

Using this then...and_then from the get-go makes it easier for me to keep in mind what I'm doing, and by extension, why I started doing it in the first place.

I discover myself using a similar pattern (with increased frequency) when working with results, although it often becomes more convoluted

(boolean_value)
  .then(||())
  .ok_or_else(|_| some_error)
  .and_then(|()| produces_a_result())

My questions:

Is there a more straightforward (or even just alternative) way to go from a boolean type to one of the Try-ish types without using an if expression?

If you encountered code like (boolean_value).then(||()).and_then(|_| stuff ), would you intuitively recognize the intent or wonder why in tarnation it was written that way?

While I wouldn't find it silly exactly, I would wonder if the author knew if was an expression.

It does imply a missing bool method (or method family) though.

I might suggest condition.then(option_method). flatten(), though? That makes it clearer you call if true, then get rid of a level of wrapping.

3 Likes

Personally, I would find the if much clearer.

3 Likes

You could start with Some or Ok if you feel it adds something.

Most common (for readable code) is to use early return but it might not fit what code you are wanting.

2 Likes