In a project, we spend most of our time naming, naming variables, naming methods, and so on. How do you generate concise names? A concise name that allows us TO think informally about what it is TO DO. And make our project more standardized. The following is a record of declaring them in JS, which is of course universal to any programming language.

One, named variables

1. Use English when naming your variables and functions

Like it or not, English is the dominant language in programming: the syntax of all programming languages is written in English, along with countless documents and educational materials. By writing code in English, you can significantly improve its cohesion.


/* Bad */

const primerNombre = 'Gustavo'

const amigos = ['Kate'.'John']


/* Good */

const firstName = 'Gustavo'

const friends = ['Kate'.'John']


Copy the code

2. Naming conventions

Choose a naming convention and follow it. It can be camelCase, PascalCase, snake_case, or any other form, as long as it is consistent. Many programming languages have traditions in naming conventions, and you can find some official recommendations or popular libraries on Github for reference.

/* Bad */
const page_count = 5
const shouldUpdate = true

/* Good */
const pageCount = 5
const shouldUpdate = true

/* Good as well */
const page_count = 5
const should_update = true
Copy the code

3. S-I-D

Names must be short, intuitive, and descriptive.

  • Short names should not take a long time, so keep them short.
  • Intuitive’s name had to sound natural, as close to common language as possible.
  • Descriptive names must reflect what it does/owns in the most effective way possible
/* Bad */
const a = 5 // "A" has no real expressiveness
const isPaginatable = a > 10 // It sounds unnatural
const shouldPaginatize = a > 10 // Use your own words

/* Good */
const postCount = 5
const hasPagination = postCount > 10
const shouldPaginate = postCount > 10 // alternatively
Copy the code

4. Avoid abbreviations

Do not use shrinkage. They only reduce the readability of the code. Finding a short, descriptive name can be difficult, but shrinking is no excuse for not doing so.

/* Bad */
const onItmClk = () = > {}

/* Good */
const onItemClick = () = > {}
Copy the code

5. Avoid contextual repetition

A name should not duplicate the context in which it is defined. If this does not reduce its readability, always remove the context from the name.

class MenuItem {
  /* Context MenuItem should be removed */
  handleMenuItemClick = (event) = >{... }/* Good for 'menuitem.handleclick ()' */
  handleClick = (event) = >{... }}Copy the code

6. Reflect expected results

The name should reflect the expected result

/* Bad */
const isEnabled = itemCount > 3
return <Button disabled={! isEnabled} />

/* Good */
const isDisabled = itemCount <= 3
return <Button disabled={isDisabled} />
Copy the code

Two, named functions

There is a useful pattern to follow when naming functions.

1. A/HC/LC model

prefix? + action (A) + high context (HC) + low context? (LC) Prefix verb/action Strong description (main content) Low description (auxiliary content)Copy the code

See the table below

Name Prefix Action (A) High context (HC) Low context (LC)
getUser get User
getUserMessages get User Messages
handleClickOutside handle Click Outside
shouldDisplayMessage should Display Message

Note: The order of context affects the meaning of a variable. For example, shouldUpdateComponent means that you are about to update a component, while shouldComponentUpdate tells you that the component will update itself, and you just control when it updates. In other words, high context emphasizes the meaning of a variable.

2. The Action Action

The verb part of your function name. The most important part describes what the function does.

2.1 get

Immediate access to data (i.e. shorthand getters for internal data)

function getFruitCount() {
 return this.fruits.length
}
Copy the code

2.2 set

Set the variable declaratively, setting value A to value B

let fruits = 0

function setFruits(nextFruits) {
 fruits = nextFruits
}

setFruits(5)
console.log(fruits) / / 5
Copy the code

2.3 reset

Sets a variable to its initial value or state.

const initialFruits = 5
let fruits = initialFruits
setFruits(10)
console.log(fruits) / / 10

function resetFruits() {
  fruits = initialFruits
}

resetFruits()
console.log(fruits) / / 5
Copy the code

2.4 fetch

Request some data, which takes some indeterminate time (i.e., asynchronous request). Personally, IT is ok to use Request.

function fetchPosts(postCount) {
  return fetch('https://api.dev/posts', {...})
}
Copy the code

2.5 remove

Remove an item from somewhere.

For example, if you have a collection of selected filters on your search page, removing one of the filters from the collection is a removeFilter, not a deleteFilter (which is also naturally said in English).

function removeFilter(filterName, filters) {
  return filters.filter((name) = >name ! == filterName) }const selectedFilters = ['price'.'availability'.'size']
removeFilter('price', selectedFilters)
Copy the code

2.6 delete

To erase something completely from the realm of being.

Imagine you’re a content editor and you have that infamous post and you want to take it down. Once you click a shiny “deletePost” button, the CMS performs the deletePost action instead of removePost.

function deletePost(id) {
  return database.find({ id }).delete()
}
Copy the code

2.7 compose

Create new data from existing data. This applies mainly to strings, objects, or functions.

function composePageUrl(pageName, pageId) {
  return (pageName.toLowerCase() + The '-' + pageId)
}
Copy the code

2.8 handle

Process an action. Usually used when naming callback methods.

function handleLinkClick() {
  console.log('Clicked a link! ')
}

link.addEventListener('click', handleLinkClick)
Copy the code

3. The content of the Context

The context in which the function operates

A function is usually an operation on something. It is important to state what its operable domain is, or at least an expected data type.

/* a generic filter operation function */
function filter(list, predicate) {
  return list.filter(predicate)
}

/* Use exactly the same method used to get the most recent post */
function getRecentPosts(posts) {
  return filter(posts, (post) = > post.date === Date.now())
}
Copy the code

4. The Prefixes prefix

Prefixes enhance the meaning of variables. It is rarely used in function names.

4.1 is

Represents a feature or state (usually a Boolean value) of the current environment.

const color = 'blue'
const isBlue = color === 'blue' // characteristic
const isPresent = true // state

if (isBlue && isPresent) {
  console.log('Blue is present! ')}Copy the code

4.2 has

Describes whether the current context has a value or state (usually a Boolean value)

/* Bad */
const isProductsExist = productsCount > 0
const areProductsPresent = productsCount > 0

/* Good */
const hasProducts = productsCount > 0
Copy the code

4.3 should

Reflects a combination of a positive conditional statement (usually a Boolean) with an action.

function shouldUpdateUrl(url, expectedUrl) {
  returnurl ! == expectedUrl }Copy the code

4.4 max/min

Represents a minimum or maximum value. Used when describing boundaries or restrictions

/** * Auto insurance random number posts * Max, min boundaries */
function renderPosts(posts, minPosts, maxPosts) {
  return posts.slice(0, randomBetween(minPosts, maxPosts))
}
Copy the code

4.5 prev/next

Indicates the previous or next state of a variable in the current environment. Used when describing state transitions.

function fetchPosts() {
  const prevPosts = this.state.posts

  const fetchedPosts = fetch('... ')
  const nextPosts = concat(prevPosts, fetchedPosts)

  this.setState({ posts: nextPosts })
}
Copy the code

5. Singular and Plurals

Like prefixes, variable names can be singular or plural, depending on whether they hold one or more values.

/* Bad */
const friends = 'Bob'
const friend = ['Bob'.'Tony'.'Tanya']

/* Good */
const friend = 'Bob'
const friends = ['Bob'.'Tony'.'Tanya']
Copy the code

Github