Faking premature returns

I am porting some Python code to Elixir, and the some functions have lot’s of premature returns:

if ...:
    return ...
# do stuff
if ...:
    return ...

What is the “accepted” way of emulating this style in Elixir? I’m thinking of using the with statement to handle the happy case and mach on “errors” in the else clause.

Long term you should obviously rewrite this in a functional style :smiley:

You could use throw and catch. throw would be the premature return and you have an outer catch wrapper returning them to the caller. If this is better than with I don’t know but may make the code easier to port by just replacing return with throw.

Can you emulate it with pattern matching and multiple function heads? They usually are the go-to techniques.

1 Like

with is perfectly fine for this, as if just if/do/else/end. But yeah more properly should rewrite it in a functional style, and as such use more functions. :slight_smile: