Sync’ up! … without getting drained

sep 30

Why I stopped writing specs

In the film ‘Redbelt,’ there’s a scene where a new student of jujitsu is in class alone with the teacher. The student — hesitant, uncooperative & still visibly shaken from a personal traumatic episode — is asked by the teacher who stands on the other side of the room: ‘where can I strike you?’ Clearly, the student is not within striking distance when the teacher stands twenty, fifteen, or even six feet away. It’s only when the teacher draws quite close that the question of ‘could I strike you, now?’ can be answered in the affirmative — ah, yes, from that distance he could strike that student. The teacher closes the scene with the remark: ‘[then] don’t stand there.’

Spaghetti-code can be found in any language. And there is nothing special about Erlang that makes spaghettification any less prevalent. With opaque and impenetrable source-code, one could insist that we need a specification for our routines so we readers of said code can know what happens within. But, when might we not need specification for our code?

Would we need it, here?

maybe_bar(foo)   -> bar;
maybe_bar(_Else) -> void.

Or, how about here?

maybe_bar(Thing) ->
    case Thing of
        foo -> bar;
        _Else -> void

How about, here? Do we need a specification for this?

argument_checkr(FooOrNot) ->
        FooOrNot =:= bar ->
            Result = bar;
        true -> Result = void

Ok, my hand went up! I am better off with a specification for the last example routine than not, as I cannot quickly read it and certainly can’t guarantee what’s going on upon a quick glance.

Although the example begs the point, you can see that the code goes from looking somewhat self-documenting, into something more of a black-box — something which requires explanation.

Obviously, if you are going to write fast-and-loose & never take time to refactor code down to a few lines, then spec away. But in Erlang, there is a way to write code that reads like English. This saves oodles of time, is easy to read & most importantly, keeps one far from striking distance (bugs).