Then...and_then ergonomics and readability

I often find myself writing something akin to the following:

  .and_then(|_| produces_an_option())

I know I could just write:

if boolean_value {
} else {

...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

  .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.


Personally, I would find the if much clearer.


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.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.