Code for Cheryl

© 2011, Martin Rinehart

I recently stumbled on a "JavaScript test" for aspiring frontend engineers. It was created by a young fellow who really knew his JavaScript. I'd fire him, unless he was pretty quick to learn better.

One of the questions was of this sort:

    a = 10;
    var a;
    alert( a );

The question is, "What does the alert say?"

A better question would be, "What does JSLint say?"¹ I trust it would tell you that the code was screwed up; that you should declare var a first and use a second. So here's the first rule of writing readable (and therefore maintainable) code:

The Cheryl Rule

Your code must be readable by the person who will be assigned to maintain it. Her name is Cheryl.

Cheryl is a bright young lady with a great attitude. She had a semester of X (where "X" is the language you are writing) four years ago in college. She was lucky (or unlucky) enough to be the only person with X on her resume when it came time to update your code. If Cheryl cannot read your code, you wrote bad code.

Clever Code Is Evil

Any sort of clever or tricky code is evil. Beginners read and write only the simplest code. Old-timers only write the simplest code, even if it is well below their reading knowledge. Here's a JavaScript example that almost rises to the level of a firing offense:

    (var wrapper = function () {
    . . .
    })();

This defines and then executes the wrapper() function. I've seen this idiom used by people who really should know better. It is both clever and tricky. Cheryl will not have a clue. It is almost a firing offense.

I say "almost" because every programmer deserves a patient explanation on first offense, especially when they can point to this idiom in a book written by a respected JavaScript guru.

There's a macho tendency among not-too-experienced coders. They want to show off what they know. They write code to try to impress other not-too-experienced programmers. Top programmers write code that Cheryl can maintain. It never shows off.


¹P. S. Today you'd "use strict"; and that wouldn't compile.

Feedback: MartinRinehart at gmail dot com

# # #