Idioms
Idioms are a big part of programming, and can often be the cause of bikeshedding
arguments. For example, in FinTech everyone knows what acct
means; do you really need
to name variables account
? Similarly, it’s an accounting idiom to use dr
and cr
for
debit and credit (although this might look odd to anyone not in the field). Idioms are
often just smaller versions of patterns.
They’re not all universally good, however. One I’ve seen recently is “remove if/else with early returns”, especially within the Ruby community. I suspect this might work with any language that allows a guard clause.
In Ruby it manifests itself thus:
def some_method(arg)
return [some_value] if some_predicate?
do_work
some_other_value # ruby has implicit "last-expression" returns
end
The sole purpose of this pattern is generally to eliminate an if/else.
def some_method(arg)
if some_predicate?
return [some_value]
else
do_work
return some_other_value
end
end
This, to me, feels like a premature optimization code-golfing exercise. Code Is For Humans(tm), so it should tell FutureDev (which might be you!) what you mean, not some clever reworking of code to do the same thing, for no other reason than it’s smaller.
My rule of thumb here is that the “early return” form with the guard clause is reserved
for checking pre-conditions of the method. I SPECIFICALLY want to return early if I
want to avoid having to “do work” because some pre-condition of the method isn’t met; the
arguments aren’t right, or some global state (ew) isn’t what I expect or some other
condition that would prevent this method from working correctly. NOT to avoid an if
.
The if
/else
is specifically that; it’s telling FutureDev that this code is making a
choice; here’s what the choice is based on, and here’s what you do if that condition is
met, or here’s what you do if it is not.
To my imperitive-programming educated brain, they’re like telling the computer “do this thing. No, wait. Check this, then if that is true/false, then do the thing I told you about before.” So it’s just another thing to push on one’s mental “stack” to have to possibly pop later. As a mentor of mine is fond of saying, “a friction, however subtle”.
As an (granted, academic) bonus, if either the positive or negative branch needs rework,
you just rework it in the branch and the structure remains the same. In the
early-return-masquerading-as-a-choice form, if you need to rework the early-return branch
with more code, you’re forced to get even MORE clever to keep that structure, or change it
to an if
/else
and put the code in as needed.
So … what about this being an idiom? Sure, it is, and I understand what is being done here when I see it, but the amount of smugness the developer gets from writing it is not much more than the subtle cognitive friction the reader has to go through to figure it out, nor is it worth the 10x amount of reading vs writing of that code.