Code specification, how to write good code

Please indicate the source:

http://blog.csdn.net/gane_cheng/article/details/52152497

http://www.ganecheng.tech/blog/52152497.html (better browsing effect)

Code specification, how to write good code

Since I went to college, whenever I saw a good article, my first reaction was to use the browser's collection function, and I collected more and more URLs over time. Although browser favorites also have folder functions that can be classified into categories, but after all, there is no blog tag that is easy to use, and only URLs can be saved. It often happens that the content is modified by the original author, or the URL becomes invalid. Taking into account that CSDN should not go bankrupt easily, and the two great gods, Brother Lu and Brother Hu , have personally set an example, and opened a CSDN blog.

As a programmer, you definitely want to be able to write good code that looks pleasing to the eye and easy to understand. It is not only convenient for you to come back and read the code in the future to understand what the code is doing at a glance, but also allow the person who takes over to get started quickly, see the subtle places, involuntarily sigh, and quietly change the bad habits of others.

How to write good code?

In a lecture, I listened to the views of a programming god and shared it with you here.

Good code should have at least the following six characteristics:

  1. Use blank lines to separate logic
  2. Use comments and curly braces
  3. Unused code and references removed
  4. Do not use Chinese pinyin for variable names
  5. Usable, clear and elegant, efficient
  6. Write more code, think more

Use blank lines to separate logic

Generally, the code exceeds about 30 lines, and we are considering whether to encapsulate these codes into a method. But even if you throw this large piece of code into a method and call this method in the main function, there is no guarantee that this method will not be modified in the future. So for yourself and others, it is still necessary to do something with the longer code.

Generally, even the code in a method, the logic can be divided into small pieces. At this time, we can add a blank line between these logics to tell others that in my code here, the code between the two blank lines is related. bigger.

Looking at the code below, without adding any comments, because there are blank lines to separate the logic, it is not a step to scare off people who want to read your code.

private void tsm_open_file_Click(object sender, EventArgs e)
{
    this.Text = "数字签名工具 - 添加文件中,请稍候...";
    if (recordList.Count > 20)
    {
        MessageBox.Show("最多支持20个文件一次性签名。");
        return;
    }

    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "程序文件|*.exe;*.dll|可执行文件|*.exe|动态链接库|*.dll";
    openFileDialog.RestoreDirectory = true;
    openFileDialog.FilterIndex = 1;
    openFileDialog.Multiselect = true;

    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        String[] fileNames = openFileDialog.FileNames;
        for (int i = 0; i < fileNames.Length; i++)
        {
            String oldPath = fileNames[i];

            if (canAddFile(oldPath) == false)
            {
                MessageBox.Show(String.Format("文件{0}不能添加,因为已经有同名文件了。", oldPath));
                continue;
            }

            FileInfo fileInfo = new FileInfo(oldPath);

            Record record = new Record();
            record.FilePath = oldPath;
            record.AddTime = DateTime.Now;
            record.FileSize = fileInfo.Length;
            record.Progress = "0% 新添加";
            String md5 = MD5Util.getMD5(oldPath);
            if (md5 == null)
            {
                MessageBox.Show(String.Format("文件{0}的MD5值计算失败,请查看文件是否被其他程序占用,或稍后再试。", oldPath));
                continue;
            }
            record.MD5 = md5;

            recordList.Add(record);
            int index = this.dataGridView.Rows.Add();
            this.dataGridView.Rows[index].Cells[0].Value = Path.GetFileName(record.FilePath);
            this.dataGridView.Rows[index].Cells[0].ToolTipText = record.FilePath;
            this.dataGridView.Rows[index].Cells[1].Value = record.AddTime.ToString();
            this.dataGridView.Rows[index].Cells[2].Value = FileSizeUtil.getFileSizeWithUnit(record.FileSize);
            this.dataGridView.Rows[index].Cells[3].Value = record.Progress;
            this.dataGridView.Rows[index].Cells[4].Value = record.MD5;
            this.dataGridView.Rows[index].Cells[5].Value = "";
        }
    }
    this.Text = "数字签名工具";
}

Use comments and curly braces

Documentation should always accompany in the life cycle of software development. In this way, the person who takes over later sees the document and knows what happened at that time. If the project team has used documents to standardize development, it must follow this rule. However, there is also a problem with the documentation, that is, after the code is modified, the documentation must be modified. If the documentation is not updated, the person who takes over will be misled.

Documentation is a good habit. While insisting on updating the project documentation, you should also remember to update the comments of the code. After typing the code, you can add a few short words, which will improve the efficiency of reading the code many times.

When you're struggling to guess what the original coders thought, seeing the commented code below does not feel like a thank goodness.

/// <summary>
/// 执行点击事件
/// </summary>
/// <param name="sender">控件</param>
/// <param name="e">事件</param>
private void tsm_open_file_Click(object sender, EventArgs e)
{
    //最大数量验证
    this.Text = "数字签名工具 - 添加文件中,请稍候...";
    if (recordList.Count > 20)
    {
        MessageBox.Show("最多支持20个文件一次性签名。");
        return;
    }

    //弹出文件选择框
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "程序文件|*.exe;*.dll|可执行文件|*.exe|动态链接库|*.dll";
    openFileDialog.RestoreDirectory = true;
    openFileDialog.FilterIndex = 1;
    openFileDialog.Multiselect = true;

    //返回选中的文件
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        String[] fileNames = openFileDialog.FileNames;
        for (int i = 0; i < fileNames.Length; i++)
        {
            //记录文件路径
            String oldPath = fileNames[i];

            //查看是否能添加
            if (canAddFile(oldPath) == false)
            {
                MessageBox.Show(String.Format("文件{0}不能添加,因为已经有同名文件了。", oldPath));
                continue;
            }

            //得到文件信息
            FileInfo fileInfo = new FileInfo(oldPath);

            //构造记录对象
            Record record = new Record();
            record.FilePath = oldPath;
            record.AddTime = DateTime.Now;
            record.FileSize = fileInfo.Length;
            record.Progress = "0% 新添加";
            String md5 = MD5Util.getMD5(oldPath);
            if (md5 == null)
            {
                MessageBox.Show(String.Format("文件{0}的MD5值计算失败,请查看文件是否被其他程序占用,或稍后再试。", oldPath));
                continue;
            }
            record.MD5 = md5;

            //添加到列表,显示到页面上
            recordList.Add(record);
            int index = this.dataGridView.Rows.Add();
            this.dataGridView.Rows[index].Cells[0].Value = Path.GetFileName(record.FilePath);
            this.dataGridView.Rows[index].Cells[0].ToolTipText = record.FilePath;
            this.dataGridView.Rows[index].Cells[1].Value = record.AddTime.ToString();
            this.dataGridView.Rows[index].Cells[2].Value = FileSizeUtil.getFileSizeWithUnit(record.FileSize);
            this.dataGridView.Rows[index].Cells[3].Value = record.Progress;
            this.dataGridView.Rows[index].Cells[4].Value = record.MD5;
            this.dataGridView.Rows[index].Cells[5].Value = "";
        }
    }
    this.Text = "数字签名工具";
}

Curly braces {} generally have two forms in the code:

  • One is the default top-bottom alignment of the C++ source code editor in Visual Studio
int main()
{
    cout<<"我是C++"<<endl;
}
  • One is the default left curly bracket at the end of the Java source code editor in Eclipse.
public class HelloWorld {
    
     
    public static void main(String args[]) { 
        System.out.println("我是Java"); 
    } 
}

The C++ default method makes it easier to see the code hierarchy; the Java default method reduces the number of lines occupied.

Personally, I prefer top-bottom alignment. But personal opinions need to obey the team agreement. Whichever method your team uses, you should use whichever method, and keep it consistent with everyone.

And these two default methods can be adjusted in the integrated development environment IDE. For example, Java code, I usually typeset like this.

public class HelloWorld
{
    
    
    public static void main(String args[])
    {
        System.out.println("我是Java");
    }
}

Unused code and references removed

When we write code, we often annotate the previous code when we need to modify the code, and then add our own code. But I am not sure that my code is 100% correct, and I dare not delete the commented code, because it may be replaced with the original code.

The consequence of this is that if you don't see the problem of the commented code in the future, but you think it makes sense, you will really replace your code with the commented code.

When we write code, we must believe in ourselves, and delete it when it is time to delete it. Learn to use SVN or Git for version control. Even if the current version is deleted, you can still get it back by rolling back to the previous version. You don't have to worry that it will be deleted, so if something goes wrong, you can still get it back.

We will also often notice that there are many yellow exclamation points warning prompts at the beginning of the editor line. Although it does not affect the normal operation of the program, it looks a bit unsightly, and too many unused references, or external packages, frameworks, libraries, etc., will also slow down the running speed of the program. Getting rid of these useless things can not only purify our minds, but also reduce hidden dangers that are not easily detected.

Do not use Chinese pinyin for variable names

Now both C# and Java support Chinese variable names and class names. You can try to play, but don't really use it in the project, not only speaking Chinese, but also Chinese Pinyin. Using meaningful English as the variable name is more conducive to communication, it is convenient to communicate with foreigners, and it is also convenient to communicate with Chinese. I have seen someone design a database, and all the field names use Chinese pinyin abbreviations, which is puzzling and very awkward, probably only I can understand it.

Don't use a, b, c, d as variable names in English variable names. Use meaningful full names to know the variable at a glance and what this class is for. Everyone is so busy that they don't have time to guess.

Usable, clear and elegant, efficient

Specific to an actual function, the code is usable, looks clear and elegant, and runs efficiently is the standard of good code.

  • To achieve these three points, we must first clarify the requirements, consider a comprehensive point, think about the problem from the perspectives of correctness, boundary value, and counter-example, set detailed requirements, and grasp the intention of the demander.
  • Secondly, you need to do a demo first, for both parties to further confirm the requirements. Without Demo, neither party is very sure whether the other party has got √ to my meaning. With Demo, most of the requirements can be determined. A rough finished product is better than a fine half-finished product. Don't optimize prematurely, make rough finished products first, and optimize later.
  • Finally, when it comes to code, it is often necessary to debug the code. Don’t debug the breakpoint as soon as it comes up. Look at the code first, check the code logic, rationalize the idea, and then use the dichotomy method to set the breakpoint output log to quickly locate the problem code. When optimizing, determine an optimization benchmark, compare after optimization, and use data to tell others the effect of optimization.

Write more code, think more

Write more code, think more; drink more hot water, exercise more.

Good code is accumulated on the basis of a certain amount of code. When writing, you need to think more, and you have to know what you are doing.

Programmers sit in chairs for long periods of time, causing a lot of damage to the spine and stiff necks. It is recommended to drink more water and do more activities. After an hour of coding, stop and rest, walk, and move. Exercise more, the body is the capital of the revolution.

Guess you like

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