News for hackers. Stuff that matters.
Re:Programming Patterns I Like by irjoe on Saturday June 29, 2019 @03:44AM (#20311337)
I'm currently writing a lot of Elixir where early returns are a feature of the language (https://hexdocs.pm/elixir/Kernel.html#module-guards).

I also write a lot of JS and tend to use guard clauses fairly liberally. I find they make boundaries (x < 0) much clearer. My functions are also < 10 lines in most cases. For me it leads to less convoluted code but YMMV.

Re:Programming Patterns I Like by sterwill on Saturday June 29, 2019 @08:45AM (#20312271)
I love Elixir, but I don't think of guards as "early returns". They're more like preconditions or filters: they prevent the function from running at all if they don't match, and because they're applied top-down in the module, it's really easy for the programmer to find the one that should match. They're great!

Other programming languages let you return from any line in the function, no matter how deep in a conditional, inside nested loops, before or after variable side effects, etc. Tricky to know just _what_ that function will do given some inputs.

Re:Programming Patterns I Like by irjoe on Saturday June 29, 2019 @09:36AM (#20312489)
You're right, they're not really "early returns" but for me at least they are often in similar fashion to the "early exit" pattern in the article:

    def transform_data(raw_data) when length(raw_data) == 1, do: []
    def transform_data(raw_data) do
        # actual function code goes here
    end
That said, I wouldn't want to see the above snippet in my team's codebase :)
Re:Programming Patterns I Like by rrobukef on Saturday June 29, 2019 @04:08PM (#20314501)
Not a fan of prolog then? As an excercise, find the guard in this snippet (https://rosettacode.org/wiki/Babbage_problem#Prolog) and imagine such code in a team codebase!
Re:Programming Patterns I Like by irjoe on Sunday June 30, 2019 @05:19AM (#20317225)
Quite the opposite :) My preference would be to rely on pattern matching (unification) in the function head:

    def transform_data([_|[]]) do: []
I just wanted an example of using guard clauses. It does depend on the actual code though, there's probably a more elixiry solution.