Hacker News new | ask | show | jobs
by thinkingeric 5622 days ago
I use an additional guideline: things that are created near where they are used can be abbreviated more than something that is created 'far away'.
2 comments

That's a good rule. I usually declare variables as close to their intended scope of use as I can get them, so for instance, right inside the block where the variable is going to be used.

The temptation then becomes to re-use the name but I avoid that to make it easier to see which declaration belongs to which variable.

Declaring all the variables at the top of a function was a pretty hard to break habit.

I tend to do the same thing. Except, since JavaScript doesn't have block scope, it all ends up at the top of the function.

Which is much more preferable than scattered around the function. Especially due to hoisting[1].

My functions typically go in the order of:

declare variables; declare any local functions if necessary (most of the time these eventually get refactored out to somewhere else, because they tend to be one-off utility functions that can be abstracted); do stuff; return value.

1. http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-...

It reminds me of Rob Pike's "Notes on Programming in C", where Pike takes frequency into account as guideline, i.e. "A global variable rarely used may deserve a long name, maxphysaddr say" [http://doc.cat-v.org/bell_labs/pikestyle - Variable names paragraph - a nice and suggested read].
Here is a quote from that essay that says it much clearer than my pithy 'guideline':

"I prefer minimum-length but maximum-information names, and then let the context fill in the rest. Globals, for instance, typically have little context when they are used, so their names need to be relatively evocative. Thus I say maxphysaddr (not MaximumPhysicalAddress) for a global variable, but np not NodePointer for a pointer locally defined and used. This is largely a matter of taste, but taste is relevant to clarity."

Huh, why not MaxPhysicalAddress[1]? "maxphysaddr" looks like my cat walked across the keyboard.

[1] or seperated by underscores or dashes in up- or lowercase wearing earmuffs

for what concerns capital letters, from the essay I cited before [http://doc.cat-v.org/bell_labs/pikestyle]: "I eschew embedded capital letters in names; to my prose-oriented eyes, they are too awkward to read comfortably. They jangle like bad typography". As Pike acknowledges this is just a matter of taste.