A flexible set of naming suggestions you can modify to your needs

Mohammed Ibrahim
Aug 21 · 6 min read
Photo by Aurélien — Wild Spot on Unsplash

There is no final word on proper naming conventions but if you feel like starting with a flexible set of suggestions and modifying to your needs, I may be able to help you.

The code in this guide is written in JavaScript but these principles can be applied in general.

1. Don’t Worry, Be Happy

const doSomething = stuff => {}

The function above is a sort of ritual of mine. Over the years, I’ve come to realize that I need a function before I actually need to name it, so I start here pretty often.

For the record, it’s accurate; I have to do something to stuff. The function’s name tells me what the function does, while also telling me to rename it soon.

Most of the time, I rename this function before I ever call it but, sometimes, I find myself working through a tough problem at the 11th hour and I need all the brainpower I can conserve.

The point I’m illustrating is that I never lose my rhythm for higher thinking just because I have to choose the right name for a variable, and you shouldn’t either.

Most modern IDEs today are built to safely rename variables across an entire project and if you want to improve your talent for naming convention, you should be leaning on that tool early and often.


2. Flatter Is Better

const THEME_BORDER_COLOR = '#999'
const THEME_BORDER_STYLE = 'solid'
const THEME_BORDER_WIDTH = 1
const THEME_MARGIN_BOTTOM = 20
const THEME_MARGIN_TOP = 20
const THEME_PADDING = 40

const theme = {
border: {
color: '#999',
style: 'solid',
width: 1,
},
margin: {
top: 20,
bottom: 20,
},
padding: 20,
}

Flat variables can be indexed by your IDE, which makes them easier to use across your project.

Also, take a look at the example above. If I wanted to change from a single PADDING variable to PADDING_TOP, PADDING_BOTTOM, and so on, I could do this easily with the flat structure by simply creating new variables.

In the nested structure, however, I’d need to change theme.padding from a value to an object with deeper nesting. Constantly reshaping your variable tree this way is bound to give you trouble as your project grows, whereas a flat structure loves to scale.


3. Avoid Abbreviations

let i = 0  ->  let index = 0
let j = 0 -> let index2 = 0

The first part of the example above looks innocent enough, right? What’s the problem with using i as an index variable?

The problem is, when you need another index variable in scope, you will be tempted to reach for j.

This is because, although j would be a natural progression, you’ve now incorrectly implied that these variables are part of a series, when i was really short for index, and j represents index2.

Opt for slightly wider code to afford yourself more descriptive names. If you name your variables and functions properly, you should require significantly less inlined documentation, because, to a degree, the code will document itself.

initAuth  ->  initializeAuthentication or initiateAuthorization

I really dislike the prefix init because it’s hard to tell if the function initiates something or initializes it. I also avoid the abbreviation auth because it could apply to authentication or authorization.

Looking at the example above, if you were to choose one of the bold names, you wouldn’t need additional documentation to make those distinctions clear.


4. Be Grammatically Consistent

In English grammar, there are four sentence structures:

  • Declarative: “The project is delayed.”
  • Imperative: “Tell me why.”
  • Interrogative: “Are you sure you want to know?”
  • Exclamatory: “Yes!”

Here are those structures in code:

  • Declarative: userIsAuthenticated (variables)
  • Imperative: authenticateUser (functions)
  • Interrogative: isUserAuthenticated (don’t use)
  • Exclamatory: AUTHENTICATION_ERROR (constants)

Declarative sentences state information, so use these for variables.

As imperative sentences prompt action, use them for functions.

Exclamatory sentences don’t really exist in code but consider constants to be in this category.

Finally, interrogative structures in code can be confusing, so avoid them.


5. Prefix/Suffix Your Names

Booleans

One of the most effective tips for helping you clean up your naming convention is to reserve certain prefixes and suffixes for specific groups of variables.

For example, I like to prefix all of my booleans with one of the following words: is, can, or should.

let active = false  ->  let isActive = false
let load = false -> let canLoad = false
let render = false -> let shouldRender = false

By ensuring all boolean variables are part of a subgroup which is expressed in the prefix, I have much more information to guide me when I’m debugging.

Arrays

There’s a common agreement around naming arrays; we all seem to agree that arrays should be pluralized. I find one weakness in that approach.

Check out this example:

const exchangeRates1 = {
EUR: {
CNY: 7.84,
GBP: 0.91,
INR: 79.42,
USD: 1.11,
},
USD: {
CNY: 7.06,
EUR: 0.90,
GBP: 0.82,
INR: 71.51,
},
}

const exchangeRates2 = {...}
const exchangeRates3 = {...}

const exchangeRates = [
exchangeRates1,
exchangeRates2,
exchangeRates3,
]

The data dictates that an object named exchangeRates{n} is a collection of values, which is fine. But, then, our array of collections is named exchangeRates with no n value, which can be confusing when you’re only looking at the name.

Does this variable represent just one of the exchange rates objects, perhaps an active object? Is it of type object or another type? How should we imply that this is an array?

Try this:

exchangeRates  ->  exchangeRatesSet

I use the suffix Set to identify arrays, rather than pluralizing. It makes for slightly wider code but you can see above how it solves the problem of collecting pluralized objects.

Functions

I do a lot of my professional work with React and Redux, and one of my favorite concepts in this stack is the selector.

Without getting into it, many Redux programmers agree that selectors should begin with the prefix get, as in getUserInfo. Therefore, it stands to reason that a non-selector function name should not begin with the same prefix.

I’d like to expand on that principle.

In almost every React/Redux project I have, there’s a folder with somewhere between five and fifteen functions which I call helpers, they are not selectors or thunks or action creators or reducers… they don’t really have a home.

These are usually pure functions, each of which does a single task.

Functions like:

isUserActive = user => {...}
canLoadItem = item => {...}
makeFormattedDate = (date, format) => {...}
sortActiveUsers = users => {...}
validateEmailAddress = (address, validations) => {...}

And I was ok with the existence of these helper functions, as long as they stayed pure and simple.

Something bothered me, however, about the fact that I couldn’t identify a helper function on sight.

As a result, I began prefixing all my helper functions with either determine or prepare, depending on whether that function returned a boolean or data.

isUserActive          ->  determineIsUserActive
canLoadItem -> determineCanLoadItem
makeFormattedDate -> prepareFormattedDate
sortActiveUsers -> prepareSortedActiveUsers
validateEmailAddress -> prepareValidEmailAddress

By ensuring that all of my helper functions are named as verb phrases with specific prefixes, I eliminate the challenge of grammatical consistency while also developing a sort of brand for my helper functions, separating them from my selectors and thunks.

Also, notice how we started with a mix of imperative, declarative, and interrogative function names, and ended with all imperative names.

Below, I have two Redux thunk functions, one calling the other:

const fetchUserDataIfNeeded = userID => dispatch => {
const fetchIsNeeded = {...}
if (fetchIsNeeded) {
dispatch(fetchUserData(userID))
}
}

const fetchUserData = userID => dispatch => {...}

Commonly, when working with asynchronous fetching, you need to call a function which makes a determination as to whether or not the data needs to be fetched or re-fetched, and if so, then the conditional function will call the fetch function.

In my Redux projects, I use the suffix IfNeeded for these cases. Now, when I see this function, I know I’m looking at a conditional async fetch thunk, which is a lot of metadata to convey in a function name.


Conclusion

Obviously, there’s so much I’m leaving out, like how classes should be nouns and how a parent with children is better than a list with items and much more… but I thrive in the six to eight-minute article demographic.

So, please, I encourage you all to challenge everything you see here. Find your own formula, as long as you find consistency.

Better Programming

Advice for programmers.

Mohammed Ibrahim

Written by

I design apps.

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade