How to write clean code in "Code Specification" (1)

insert image description here

Hello everyone, I have been busy recently, and the updates have become irregular. Next, I will try my best to make my sharing more stable... Please follow, collect, like... Thank you very much

foreword

I don’t know if I have found that many excellent open source projects often have clear code structure and complete annotations. Both their readability and scalability are very powerful. I am very envious. Therefore, how to write clean and excellent code It is the first step to promotion to the big brother;

At this point, some friends may ask, what kind of code is clean code? Don't worry, this question is the conclusion we finally came to, and then record some points that I personally think are necessary for clean code;

naming convention

The first one, of course, is the naming rules. When looking at the source code of such excellent projects as Vue, I found that there are relatively few annotation-related content, but through the method name, function name, variable name, etc., we can roughly see its content. What is the function, here is the so-called naming should have its corresponding meaning instead of writing whatever comes to mind , for example:

function UsEntity(){
    
    
  // 代码
}
const us = new UsEntity();

In this example, a function UsEntity is defined, and it feels like this should be a constructor function, because according to the convention the first letter is capitalized and there is a word Entity which means an instance, and it is also used below, if you don't write a comment Only based on the name, we can't guess the specific function of this code with high probability, so obviously this is not very good, if you change it

function User(){
    
    
  // 代码
}
const user = new User();

Then this is very clear, that is, the user, defines a constructor function about the user, and instantiates a user below, the next operation must also be related to the user; in
this way, a good name is really important, it can Help us quickly understand the general function of a function or variable when comments or related documents are not so complete ;
then the question is, what does the naming rule look like? I think this is still the score:

Variables and Constants

For variables and constants, their functions are often used for data storage, state control, etc. I think the more appropriate rules are: noun or phrase + adjective :

// 用户信息
const user = {
    
    };
const age = 12;
const name = "oliver";

// 验证结果,比如是否已登录
const isLogin = false;

I personally think this is more appropriate. Relatively through the variable name, we can see its general function. In addition, we often use the small camel case for the variable name , but this is not absolute. This needs to be defined according to each team. For constants , we usually use all-caps specification, and words are separated by underscores, for example:

const USER = {
    
    };

At this point, some small partners may say that this naming is too simple. In actual projects, it is often repeated. At this time, we can describe this variable in more detail, but the degree of attention should not be too much. That way It will appear too redundant. For example, for the data stored in the foreground, we generally use user for the user information stored in the foreground, but what if there are multiple users, then we can add some prefixes

// 比如,已经认证过的用户
const authenticatedUser = {
    
    };
// name
const firstName = "";
// 是否激活
const isActiveUser = false;

Small exercise
topic: naming of stored user information

// 比较差的命名
const u = {
    
    };
const data = {
    
    };

This is the kind of naming that I personally think is relatively poor, because the user cannot be seen at all by looking at the variable name, and the scope of data is too wide, and a lot of data can be represented by data;

// 正常
const userInfo = {
    
    };
const userData = {
    
    };

Some friends may say, this is not very good, why can only say normal, I personally feel that the variable name is a bit redundant , user is also a noun, it can already represent the current variable used for user-related content, can not Need to add info and data;

// 比较好的
const user = {
    
    };
const customer = {
    
    };

For a better naming, it should be concise enough and be able to explain its purpose. User and customer can fully explain its function and are very concise, so I personally think it is more appropriate;

functions and methods

For functions and methods, their role is often to perform some operations or commands, and to calculate some results, such as requesting interfaces and validating forms. I think the more appropriate rules are: verbs or phrases + adjectives :

// 发送用户信息
function sendUser(){
    
    };

// 获取用户信息
function getUser(){
    
    };

For functions and methods, we generally follow the small camel case specification , unless the function is a constructor . For constructors, we agree to name them in large camel case ;
similarly, function names and method names can also be further described, can increase its accuracy and the possibility of no duplicate names, such as

// 获取用户信息
function getUserByPhone(){
    
    };

This is very suitable, and you can see the function of this function at a glance, get the user through the mobile phone number, and of course some verification, calculate the Boolean value:

function phoneIsValid(){
    
    }

You should be able to see the function of this function by looking at the name, to determine whether the phone has passed the verification function;

Small exercise
topic: Storing user information in a database

// 比较差的
function handle(){
    
    }

I think this is relatively poor, or the reason for the above variable, the scope is too wide, through the variable name handle, we can know that this is an operation, but we don't know the specific operation at all, obviously, this is not great fit;

// 正常
function save(){
    
    }

This is relatively better. We know that this is a save function, but in the process of writing, maybe we can know what it is to save, but after a period of time, we can only know that this is a save operation just by looking at the name. , it is completely unknown what to save;
compared to handle, the advantage of save is that it can specifically know the type of an operation, but it is unknown what this operation is for;

function saveUser(){
    
    }

Obviously, this intention is relatively clear, that is, to save users, so this kind of thing is more appropriate and better named;

class class

For the class class, I think the biggest use is to construct abstract things, such as users and products. For this, I feel that its rules can be similar to variables, and the rules are roughly the same: nouns or phrases + adjectives :

// 用户
class User{
    
    }
class Customer{
    
    }

// 飞机游戏
class PlaneGame{
    
    }

For the class name, we often use the big camel case, because the definition of the class is often the constructor;

Small exercise
topic: define a user object;

// 较差的
class UEntity{
    
    }

This kind is relatively poor, and I can't see what its meaning is at all... I can only feel that it is an entity of U, and I can't guess;

// 普通的
class UserObj{
    
    }

This is very common. Looking at the name, we can know that this is an obj collection about the user, but it is a bit redundant.

class User{
    
    }
class Admin{
    
    }

This is very good. You can directly know its function by looking at the name. Admin is the specific authority division of User. Sometimes we need more specific user information, so it can be represented by a more specific name;

other

It is not recommended to describe variables with more than 3 words, such as

// 不太建议
const userWithNameAndAge = ""

Although we can quickly know its function and meaning by looking at the name, it is actually too redundant. Name and age are generally fixed attributes of the user. In fact, name and age are not needed.

// 新用户
const newUser = "";
// 已登录用户
const loggedInUser = "";

Code Structure and Format

Notes

First of all, we need to make it clear that comments are explanations and descriptions of the code. The purpose is to let others understand the functions and business more easily and quickly when reading the code written by the author. Therefore, good comments can be used to synergize and change bugs. A bad comment is a complete hindrance. I didn’t understand it at first, but after reading the comment, it’s even more ambiguous…

bad note

Just look at the example

// 冗余的注释
function getUserName(type) {
    
    
    if (type === "first") {
    
    
        // 如果type的值等于first返回first name
        return "first name";
    } else {
    
    
        // 否则返回last name
        return "last name";
    }
}

What's wrong with this? Obviously, we can quickly understand the meaning of the code without reading the comments, but once the comments are written, we need to spend extra effort to read them, which is not suitable. The original intention of the comments is to assist faster reading. , here is a bit of putting the cart before the horse ;

The second kind of comment is also annoying , that is , the naming of the variable name and the comment are conflicting , such as

// 变量名和注释冲突
function insertUser(user) {
    
    
	this.dbEngine.insert(user)	// 更新用户
}

It is similar to this. Insert generally represents insertion, but the comment here is update. The word generally used for update is update, so once other developers see this comment, they have to look at the specific implementation. Logic, to determine whether this method is insert or update, so the annotation must be consistent with the variable name and cannot be misleading ;

The third type of comment is the commented out code . This is actually quite helpless. As the project gets bigger and bigger, the uncertain code at that time is temporarily commented out. Maybe the original intention at that time was to have another solution, but not necessarily Yes, the commented-out code needs to be temporarily saved, but as the development progresses, the commented-out code is often kept forever, and the person who takes over does not dare to delete it at will, so in this case there are generally two recommend:

  • When reviewing the code, be sure to review the commented out code, review the situation after discovery, and determine whether it needs to be deleted;
  • Once the function is determined, the developer must consciously delete the commented out code, otherwise the pit will be kept forever;

good note

If there are bad ones, there must be good ones. Good comments generally include the following:

  1. Copyright information , including time, version, legal information, author information, etc., which can quickly help others contact the author when they have questions;
  2. Supplements to variable names , such as information that cannot be described by variable names,
// 邮箱 [text]@[text].[text],邮箱只有一个"@"和一个"."
const emailRegex = /\S+@\S+.\S+/
  1. The description of warning information , such as some code has applicability or functional attention points, can be expressed through comments
// 仅使用于浏览器环境
localStrage.setItem("user","name")
  1. Unfinished code , such as when the code was not written due to special reasons, you can write a note to remind
function getUser(){
    
    
  // 待办事项,需要实施
}

code format

The code format is simply divided into two types, one is between lines (such as blank lines between lines), and the other is between the same line (such as indentation), but no matter what, we The purpose is to improve readability;

line to line

In principle, the code between lines should not have too many jumps. Simply put, it is not to let people scroll back and forth. In order to achieve this purpose, we generally have the following considerations

  • Consider splitting files with multiple concepts . For example, there are many classes in a file, then you can consider splitting each class as a file at this time;
  • In the same file, different "areas" should be separated by intervals . For example, in a large functional interface, there are two functions of adding and modifying , so the newly-added related functions should be written together, and the modified related ones should also be written together;
  • In the same file, related functions should be as close as possible , such as adding and querying. Generally, we need to refresh the content of the table after the content of the table is added successfully. If the two areas are very far apart at this time, then It will cause inconvenience to our reading, such as the following example:
// 起始
function start(){
    
    
  next()
}

// 下一步
function next(){
    
    
  last()
}

// 结尾
function last(){
    
    }

This kind of relative is more reasonable. The functions are written in order, so when reading, you can read in order, which greatly facilitates our understanding;

Same line

Personally, I think the most important point in the rules of the same line is that the code line can be read normally without scrolling horizontally , that is, try not to appear scroll bars. Generally speaking, we will have the following rules:

  • Indentation , the indentation needs to be determined according to the actual situation of the team, a tab can be 2 spaces or 4 spaces;
  • Split long sentences into multiple short sentences , this splitting will help reading comprehension;

summary

The first section of this article explains how to write in order to facilitate reading and understanding from the naming rules of variables, functions, classes, etc. The second section describes some points of attention during development from comments to code formats . The overall summary is as follows:

  • The naming rules of variables, functions, and classes can be described by: noun or phrase + adjective ;
  • Good comments can supplement and help readers quickly understand when reading the code. Too many comments and misleading comments will greatly increase the cost of understanding;
  • It is necessary to judge whether there is a certain correlation between the upper area and the lower area between the lines of the code . If there is, it does not need to be separated. If not, it needs to be divided into blank lines;
  • There should be indentation between the same line , and the code length should not be too long to appear scroll bars ;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324475592&siteId=291194637