There are only two hard things in Computer Science: cache invalidation and naming things.

– Phil Karlton

Be semantic

Think about the meaning of what you’re naming. Is it going to be a number, an array, an object? Most languages have rules regarding classes or exported functions being capitalized such as:

class Computer

It’s also clear in that example that Computer is a noun. Nouns are excellent places to start: What is the THING that you’re talking about in your code? Start there - name it that.

Be functional

Once you have your nouns, you should consider your verbs. If you’re naming a function, what is the function doing - it’s always a verb. Calculating - Addition? Subtraction? Presenting? Initializing? Reading? Writing?

Use these verbs:

function initPerson() {
    // Do something to initialize Person
}
function addReciept(reciepts) {
    // Take the reciepts and add them!
}

Break it down

If your module, class or function has too many nouns and verbs associated with it, maybe it’s programmatically doing too many things. Break it apart into separate functionality, and name those things separately. You may find a better way to modularize your program!

Be clear & consistent

You must be consistent with the team’s naming requirements. This helps everyone with the ability to read and understand the code you write.

If a variable name is sorted, it isn’t giving me a clear idea of what is being sorted. Is it already sorted? Where in the code did that happen?! Or, is the variable being assigned to a function that will be doing some sorting?!

const alpha_sort = (alpha_list) => {}
const int_sort = (int_list) => {}

Two functions: One sorts thru the alphabet, and the other thru integers.

Since JavaScript is weakly typed, sometimes it’s necessary to put int or str or alpha in our function and variable names. In strongly typed languages, these types can already be apparent by the inherent way the functions and variables are declared.

Shorter is better

It’s also best not to repeat ourselves when we don’t have to.

Let’s go back to our Computer class.

What are possible characteristics of a Computer? Type (laptop, desktop), Operating system (Mac OS, Linux), Manufacturer (Apple, Dell), Processor, Display…

When refering to each of these, we don’t have to repeat anything about the computer. We can simply write Computer.type or Computer.manufacturer or Computer.os

Write it out just as you would if you were writing a sentence in English: “What is your computer’s operating system?” You wouldn’t say “What is your computer’s computer manufacturer?”

If you don’t know what a thing should be called, you can’t know what it is. If you don’t know what it is…

Happy coding!

E


Got Questions❓, Comments 🗣 or Edits ✍

Use the Twitter thread below and hashtag #E4Everything to get in touch with me regarding this blog post:

Previous: Error HandlingNext: Making HTTP Requests