siniradam
siniradam

Reputation: 2929

Having hard time with selecting appropriate variable names

I'm mostly developing in JS, but since React and his friends entered my life I feel like I'm writing much more variable names, more than I used to do and I'm having troubles with naming them.

Usually trying to pick something that I can remember and someone else can remember too, also trying to be logical and not annoyingly long.

So for instance in a messaging app, user might represent logged in user, recipient user, or user API.

What I do is usually user refers to any other user in the system. me refers to the logged-in user. API depends...

What do you do? Is it something that should be camelcase with long variable names?

userLoggedIn, userRecepient, userAPI etc? Is there a commonly used pattern or a source (book, community, etc.) that I can look up to?

Upvotes: 1

Views: 832

Answers (2)

greeneley
greeneley

Reputation: 117

The naming variable is one of the hardest problem in computer science, so it's not surprised that you feel difficult when naming variable.

Is there a commonly used pattern or a source (book, community, etc.) that I can look up to? -> Unfortunately, there's nothing common structure to do it. It's up to your project and your experience.

As a 4-year experience as developer, I can share you some tips to do it:

  1. Don't make the name too abstract. Let's image that you're new in the project, when you see the variable or function, you must understand what this function do.

  2. Always use the verb as the first in the function

  3. Use the "has/have" with noun and "is" with adjective

For example:

 - "hasSavedRow", not "isSavedRow"
 - "isSelected", not "hasSelected"
  1. Apply the PascalCase for interface, namespace, component, type.
  2. Apply the CamelCase for function, callback, variable

Upvotes: 1

August Karlstrom
August Karlstrom

Reputation: 11377

My strategy is to first think about what the variable stands for in the most general sense. In your example it's a user. Then I prefix the noun with attributes which makes it sufficiently precise. In your example it would be loggedInUser or currentUser, and recipientUser. I would not recommend the name userLoggedIn in this context because it sounds like a truth value (boolean variable). For boolean variables I start by thinking of an adjective and add nouns in front of it.

Upvotes: 1

Related Questions