[erlang-questions] Variable naming conventions

Michael Turner leap@REDACTED
Mon Apr 5 10:08:45 CEST 2010


>A really common case of iteration is when process state is updated.
>Something like this:
>
> handle_call(_, #state{name=Name}=State) ->
>   UpdatedName = strip_white_space(Name),
>   {noreply, State#state{name=UpdatedName)}}.
>
> This isn't an awful example, but tacking "Updated" onto a variable
> that changes just feels too arbitrary and it's too long.

Well, if you really must make every variable self-descriptive, you could
pass UnstrippedName and update it to Name.

But consider this:

---
handle_call(_, #state{name=S}=State) ->
  N = strip_white_space(S),
  {noreply, State#state{name=N)}}.
---

I almost immediately understand S to mean "some string", and N to mean
"a (more proper) name for the state in question"; I immediately
understood that handle_call might get an unstripped string as a name;
and that names in state records should be stripped.

The really important thing that's happening here is that a name is being
put into more canonical form.  Shorter variable names with only a hint
of meaning will "stand out of the way", so that someone reading your
code can more easily see what sort of canonical form is required.

Maybe I'm old school, but variable names should generally be short, and
functions should be so short so that you can usually see ALL of the
context of use for a variable, and thereby infer a great deal about its
meaning, whenever you're in doubt.  When I see code with lots of
variable names spelled out, I don't think, "Ah, wonderfully
self-documenting code!"  I think, "Uh-oh, maybe I'm looking at code
so poorly structured that every variable has to explain itself at every
point.  Worse, I'll have a harder time figuring out the poor structure,
because it's harder to see structure even in well-structured code after
it's been bulked out with long variable names."

Don't bother trying to come up with some near-optimal factoring the
first time -- refactor *all* the time ("without mercy" as some say.) 
If you're afraid to do that because you're afraid of breaking things,
the problem is not with the habit of refactoring, it's that you're not
paying enough attention to testing.

-michael turner


More information about the erlang-questions mailing list