As we all know, software development is not a one-man job and always requires teamwork. Therefore, the naming convention of the definition must be maintained. Choosing the right name for a function or variable takes experience and a lot of code-reading time. The challenge is not a technical or management challenge, but a skill that requires a lot of practice.

Why is it so important?

1. Better communication

  • Developing products is always a team effort, and it takes making sure everyone understands the names we name, and we have to name them clearly.

2. Easy to manage

  • Because of differences in coding conventions, developers do not hesitate to touch peer members’ code.

3. Easy to audit

  • Consistent code conventions make checking easier because we don’t have to find meaning.

4. Ease of entry

  • For new developers, coding conventions make it easy to learn the insides of code by simply looking at it.

How to write a meaningful name?

  • The name of a variable, function, or class should answer all the big questions. It should tell you why it exists, what it does and how to use it. If a name requires comments, the name does not show its intent.
  • Variable names must define an exact description of their contents so that they can be self-documented without documentation.
// Bad 
let d // Time elapsed (days)
// Good
let elapsedTimeInDays
Copy the code

Use easy-to-read names

// Bad
class NwClmDmg {
    private _lyt = 'dashboard';
    private Date _modymdhms;
}
// Good
class NewClaimDamage {
    private _layout = 'dashboard';
    private Date _modificationTimestamp;
}
Copy the code

Use searchable names

  • If a variable or constant can be seen or used in more than one place in the body of the code, you must give it an easily searchable name.
// Bad
for (let item = 0; item < 34; item++) {
    s += (t[item] * 4) / 5;
}
// Good
let realDaysPerIdealDay = 4;
const WORK_DAYS_PER_WEEK = 5;
let sum = 0;
for (var item = 0; item < NUMBER_OF_TASKS; item++) {
    let realTaskDays = taskEstimate[item] * realDaysPerIdealDay;
    let realTaskWeeks = (realTaskDays / WORK_DAYS_PER_WEEK);
    sum += realTaskWeeks;
}
Copy the code

Use a consistent language, identifying and using a natural language for naming, such as using mixed English and Bahasa names can lead to inconsistency and difficulty understanding. There is no limit to the length of variable names; use sufficiently short and sufficiently long variable names in each code scope.

While short, cryptic variable names should be avoided in favor of longer descriptive names, that doesn’t mean you should use whole sentences. Extremely long names are inefficient because they make the code dirty, hard to read, and lead to typing errors.

Before we start defining conventions, here are some common delimiting conventions used in code:

  • Words are separated by underscores.
const first_name;
Copy the code
  • Words are separated by capital letters.
const FirstName;
Copy the code
  • Separate words with capital letters, except for the first letter.
const firstName;
Copy the code

Hungarian notation (archaic, obsolete and should not be used)

  • The symbol describes the type or purpose of the variable at the beginning of the variable name, followed by a descriptor that describes what the variable does. The hump notation is used to separate words.
let arrCompanyGroup; // Array called "Company Group"
let sUserName;       // String called "User Name"
let iRandomSeed;     // Integer called "Random Seed"
Copy the code

Naming conventions

Consistency and readability are key ideas that should be used in variable naming. No matter how you choose named variables, you should always ensure that naming conventions are consistent throughout your code. Consistency makes it easier for others to understand your code. In most cases, variables are declared using camelCase.

Named variables:

let firstName = 'JavaScript';
Copy the code

Named constants:

const SECONDS = 60;
Copy the code

Named Booleans:

  • likeis.are.hasSuch prefixes help developers distinguish a Boolean variable from another by simply looking at it.
let isVisible = true;
let hasKey = false;
Copy the code

Named functions:

  • The function names are written using camelCase. Always start the function name with a verb that defines the operation that the entity name affected by the function is trying to perform with the function.
getOrder();
fetchClaims();
deleteOrder();
connectToDatabase();
Copy the code

Naming method:

  • Like functions, method names are written in camelCase. Since the class name itself describes entities, it makes no sense to add entities to the function name because it becomes self-explanatory when using class methods.
class User {
    delete(id) {
        // do something}}const user = new User();
console.log(user.delete(2)); // delete the user with ID = 2
Copy the code

After class:

  • You should declare a class in your own file using PascalCase.
class UserInfo {
    constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName; }}const userInfo = newThe UserInfo (" John ", "Doe");Copy the code

Named component:

  • Components also make extensive use of PascalCase declarations. When using a component, it is distinguished from native HTML and Web components because the first letter is always written in uppercase.
function UserProfile(user) {
    return (
        <div>
            <span>First Name: {user.firstName}</span>
            <span>Last Name: {user.lastName}</span>
        </div>
    );
}
Copy the code
<div>
    <UserProfile
        user={{ firstName:John',lastName:Doe'}} / >
</div>
Copy the code

Named private property:

  • Private and protected properties in a class must be prefixed with a single underscore.
class User {
    constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.name = _getName(firstName, lastName);
    }
    _getName(firstName, lastName) {
        return `${firstName} ${lastName}`; }}var me = newThe User (" John ", "Doe");console.log(me.name);
Copy the code

Named parameter:

  • Using self-explanatory parameter labels makes it more clear what the intent of the parameter is.
// Bad
function getRemainder(x, y) {
    // do something
}
// Good
function getRemainder(number, divisor) {
    // do something
}
Copy the code

Bracket style:

  • Two common conventions for parentheses are: K&R parentheses and Allman parentheses. “K&R style” parentheses are recommended because they save a line and look natural.
  1. K&R parentheses:
if(isVisible) {
    // do something
}
Copy the code
  1. Allman, parentheses:
if(isVisible)
{
    // do something
}
Copy the code

The magic number

Magic numbers indicate that we are assigning numbers that have no clear meaning. Sometimes we use values for a specific purpose without assigning values to meaningful variables. The problem is that when someone uses your code, that person doesn’t know what that direct value means.

//Bad 
for(let i = 0; i < 50; i++){
    //do something
}
//Good 
let NUMBER_OF_STUDENTS= 50;
for(let i = 0; i < NUMBER_OF_STUDENTS; i++){
    //do something
}
Copy the code

Deeply nested

Sometimes we use nested loops that are hard to understand. The way to deal with this problem is to extract all loops into a single function. Suppose we have an array of another array of another array, and we want the value of the last array. We can write a nested loop to suit our needs. But this is not the right approach. Here, I’ve written a function that does the same thing, but it’s cleaner, easier, less repetitive, easier to read, and more reusable.

// bad practice
const array = [ [ ['Shoaib Mehedi'] ] ]
array.forEach((firstArr) = >{
    firstArr.forEach((secondArr) = > {
        secondArr.forEach((element) = > {
            console.log(element); })})})// good practice
const array = [ [ ['Shoaib Mehedi']]]const getValuesOfNestedArray = (element) = > {
    if(Array.isArray(element)){
        return getValuesOfNestedArray(element[0])}return element
}
getValuesOfNestedArray(array)
Copy the code

Avoid functions that are too large

When a function or class is much larger, it is recommended to divide it into integers. This will make our code easier, cleaner, easier to understand, and reusable. Suppose we need to add or subtract two numbers. We can do this with a feature. But a good idea is to split them into two parts. If there are separate functions, they can be reused throughout the application.

// bad 
const addSub = (a,b) = > {
    // add
    const addition = a+b;
    // sub
    const sub = a-b;
    return `${addition}${sub}`;
}

// good 

const add = (a,b) = > {
    return a+b;
}

const sub = (a,b) = > {
    return a-b;
}

Copy the code

Code duplication

Duplicate code is when a block of code is repeated multiple times in your code. This means that parts of your code need to be extracted into functions. This is the example we used earlier in “Deep nesting” above. Look at part one: We’ve done the same thing three times. A solution that makes a single function perform the same operation is a better solution. Again, this is reusable.

// bad 
const array = [ [ ['Shoaib Mehedi']]]; array.forEach((firstArr) = >{
    firstArr.forEach((secondArr) = > {
        secondArr.forEach((element) = > {
            console.log(element);
        });
    });
});

// good 
const array = [ [ ['Shoaib Mehedi']]];const getValuesOfNestedArray = (element) = > {
    if(Array.isArray(element)){
        return getValuesOfNestedArray(element[0]);
    }
    return element;
}
getValuesOfNestedArray(array);
Copy the code

Avoid one-letter variable names

One-letter variables are very, very difficult things to use. Do not use it as a variable name. But in the loop, we use some variables with letters that we can use.

// bad
const q = () = > {
    //....
}
// good
const query = () = > {
    //....
}
// It doesn't matter
for(let i = 0; i <10; i++){
    / /...
}
Copy the code

The last

❤️ Three things to watch:

If you find this article inspiring, I’d like to ask you to do me a small favor:

  1. Like, so that more people can see this content, but also convenient to find their own content at any time (collection is not like, are playing rogue -_-);
  2. Pay attention to us, not regular points good article;
  3. Look at other articles as well;

🎉 You are welcome to write your own learning experience in the comments section, and discuss with me and other students. Feel free to share this article with your friends if you find it rewarding.

Mind cruise (Shenzhen) Web front – end push (0 ~ 3 years work experience)! If you’re passionate about technology… # Gold boiling point # juejin.cn/pin/6957665…