6 tips for writing good, clean code

ringa_lee
Release: 2023-03-16 08:32:02
Original
1257 people have browsed it

Abstract:As a developer, writing clean code is very important, so in this article the author first lists some benefits of writing clean code, and then proposes 6 tips for writing clean code. , for developers to learn from. ...

Writing clean code is not an easy task and requires trying different techniques and practices. The problem is, there are so many practices and techniques on this issue that it's hard for developers to choose, so simplify the issue a bit. In this article, we will first discuss some of the benefits of writing clean code, and then we will discuss 6 tips or practices for writing the most common clean code.

The following is the directory content:

Benefits of writing clean code
1. Easier to start and continue a project
2. Conducive to the training of new team members
3. Make it easier to follow coding patterns

Tips for writing clean code
1. Write readable code
2. Use meaningful names for variables, functions and methods
3. Let each function or method perform only one task
4. Use comments to explain code
5. Maintain code style consistency
6. Check your code regularly

Some ideas about writing clean code

Benefits of writing clean code

First understand writing clean code some benefits. One of the main benefits is that clean code reduces the time spent reading and understanding the code. Messy code will slow down any developer and make the developer's job more difficult. The more confusing the code, the more time developers need to spend to fully understand it so they can use the code. And if the code is too messy, developers may decide to stop reading it and write it themselves from scratch.

1. Make it easier to start and continue a project
Let’s start with a simple example to illustrate this problem. Let’s say we return to a previous project after a long period of time, perhaps during that time a client contacts us to do another job. Now, imagine how bad and confusing it would be after first seeing the code if you didn't write clean code back then. Also, you can see how difficult it is to start coding from where you left off.

Therefore, more time must now be spent on the project because we need to understand the code we wrote before. This could have been avoided if clean code had been written from the beginning, but now the price must be paid. Also, the old code is so messy and bad that we might decide to start from scratch. Customers may not be happy to hear this.

On the other hand, clean code usually doesn't have this problem. Suppose the previous example was the opposite, and the previous code was clean and elegant, how long would it take to understand it? Maybe it would only take a few minutes of reading the code to understand how everything works, and we might have been writing it for a while , so the energy spent in this case will be significantly less than the first case, and at the same time, the customer will not care too much.

This is the first benefit of writing clean code, and it applies not only to your own projects, but also to the work of other developers. Clean code gets things started faster, no one needs to spend hours poring over code, instead we can get straight to work.

2. Conducive to the training of new employees on the team
Another benefit of writing clean code is closely related to the first benefit, that is, it can make it easier and faster for new employees Use code wisely. Suppose we need to hire a developer, how long will it take for her to understand the code and learn to use it? Of course this depends on the situation. If our code is messy and poorly written, she will need to spend more time learning the code. On the other hand, if the code is clean, readable, and simple to understand, she will be able to start her work faster.

Some people may say that this is not a problem because other developers can help her. Of course this is correct, but help should only take a short time, two or three times or a day or two, not two or three weeks. So the decision to hire another developer was made to speed up our work, not to slow it down or spend more time helping her learn to code.

When we strive to write clean code, others will learn from us, and it will be easier to follow suit and write clean code. Of course, some time still needs to be set aside to help each new developer learn and understand the code. Of course, I mean days, not weeks. Additionally, clean code will help the team bring more developers on board and help them understand the code at the same time. Simply put, the simpler the code, the easier it is to interpret and the fewer misunderstandings it will have.

3. Easier to follow coding patterns
One thing to remember is that understanding and learning how to use code is the same thing. However, this is just the beginning, and we also need to ensure that developers are willing to follow our coding model. Of course, it's easier to achieve this goal with clean code than messy code. This is important because the team not only wants to write clean code, but maintain that pattern over time, which also requires long-term thinking.

Also, what if the developer doesn't follow the current coding pattern? This problem can usually be solved on its own. Suppose there is a group of people working on the same code base, and one of them starts to deviate from the standard style. The rest of the team will then push this developer to follow the standard. She will take the advice because she doesn't want to leave the group.

There is also a situation where a developer will convince the rest of the team to adopt and follow his or her coding pattern. It's certainly a good thing if developers come up with coding patterns that are cleaner and lead to better results. Indeed, writing and maintaining clean code does not mean that any opportunity to improve it should be ignored. I believe that one should always maintain an improveable attitude towards the current practice and work hard to find opportunities for improvement.

So if a developer deviates from the current model and her model is better, then it might be appropriate for us to make the change. So we shouldn't ignore other people's coding practices before trying other patterns, and we should continue to look for room for improvement. Finally, the third scenario. The developer decided neither to adopt our practices nor to convince us to adopt hers. Because she will decide to leave the team.

Tips for writing clean code

In addition to discussing the benefits of writing clean code, it is also time to learn some techniques to help us achieve this goal. As you'll see below, clean code consists of and follows a few methods. These methods make code cleaner, more readable, easier to understand, and simpler. Of course it is not necessary to implement all methods, implementing and following one or two measures is enough to bring about positive results.

1. Write readable code
It is true that the code written will be interpreted by the machine, however this does not mean that the readability and understandability of the code should be ignored, because there will always be another person in the future Use the code we wrote. Even if we make our code inaccessible to others, we may be able to pick it up again in the future. For these reasons, it is in our own interest to make our code easy to read and understand. So how to achieve it?

The easiest way is to use spaces. You can minify your code before releasing it, but there's no need to make it look minified. Instead, use indentation, newlines, and blank lines to make your code structure more readable. When you decide to go this route, your code becomes significantly more readable and understandable. Then, looking at the code makes it easier to understand it. Let’s look at two simple examples.
Code:

// Badconst userData= [{userId: 1, userName: 'Anthony Johnson', memberSince: '08-01-2017', fluentIn: [ 'English', 'Greek', 'Russian']}, {userId: 2, userName: 'Alice Stevens', memberSince: '02-11-2016', fluentIn: [ 'English', 'French', 'German']}, {userId: 3, userName: 'Bradley Stark', memberSince: '29-08-2013', fluentIn: [ 'Czech', 'English', 'Polish']}, {userId: 4, userName: 'Hirohiro Matumoto', memberSince: '08-05-2015', fluentIn: [ 'Chinese', 'English', 'German', 'Japanese']}]; // Betterconst userData = [ { userId: 1, userName: 'Anthony Johnson', memberSince: '08-01-2017', fluentIn: [ 'English', 'Greek', 'Russian' ] }, { userId: 2, userName: 'Alice Stevens', memberSince: '02-11-2016', fluentIn: [ 'English', 'French', 'German' ] }, { userId: 3, userName: 'Bradley Stark', memberSince: '29-08-2013', fluentIn: [ 'Czech', 'English', 'Polish' ] }, { userId: 4, userName: 'Hirohiro Matumoto', memberSince: '08-05-2015', fluentIn: [ 'Chinese', 'English', 'German', 'Japanese' ] } ];
Copy after login

Code:

// Badclass CarouselLeftArrow extends Component{ render(){ return (    );}}; // Betterclass CarouselLeftArrow extends Component { render() { return (    ); } };
Copy after login

2.为变量、函数和方法使用有意义的名称
来看一看第二个技巧,它将帮助我们编写可理解和干净的代码。这个技巧是关于变量、函数和方法的有意义的名称。“有意义的”是什么意思?有意义的名字是描述性足够多的名字,而不仅仅是编写者自己才能够理解的变量、函数或方法。换句话说,名称本身应该根据变量、函数或方法的内容和使用方式来定义。
代码:

// Badconst fnm = ‘Tom’; const lnm = ‘Hanks’const x = 31; const l = lstnm.length;const boo = false; const curr = true;const sfn = ‘Remember the name’; const dbl = [‘1984’, ‘1987’, ‘1989’, ‘1991’].map((i) => { return i * 2; }); // Betterconst firstName = ‘Tom’; const lastName = ‘Hanks’const age = 31; const lastNameLength = lastName.length; const isComplete = false;const isCurrentlyActive = true; const songFileName = ‘Remember the name’; const yearsDoubled = [‘1984’, ‘1987’, ‘1989’, ‘1991’].map((year) => { return year * 2; });
Copy after login

然而需要注意的是,使用描述性名称并不意味着可以随意使用任意多个字符。一个好的经验则是将名字限制在3或4个单词。如果需要使用超过4个单词,说明这个函数或方法需要同时执行很多的任务,所以应该简化代码,只使用必要的字符。

3.让一个函数或方法只执行一个任务
当开始编写代码时,使用的函数和方法看起来就像一把瑞士军刀,几乎可以处理任何事情,但是很难找到一个好的命名。另外,除了编写者,几乎没有人知道函数是用来做什么的以及该如何使用它。有时我就会遇到这些问题,我在这方面做的很不好。

然后,有人提出了一个很好的建议:让每个函数或方法只执行一个任务。这个简单的建议改变了一切,帮助我写出了干净的代码,至少比以前更干净了。从那以后,其他人终于能够理解我的代码了,或者说,他们不需要像以前一样花很多时间去读懂代码了,功能和方法也变得更好理解。在相同的输入下,总是能产生相同的输出,而且,命名也变得容易得多。

如果你很难找到函数和方法的描述性名称,或者需要编写冗长的指令以便其他人可以使用,那请考虑这个建议,让每个函数或方法只执行一个任务。如果你的功能和方法看起来像瑞士军刀一样无所不能,那请你执行这个方法,相信我,这种多才多艺不是一种优势。这是一个相当不利的情况,可能会产生事与愿违的结果。

附注:这种让每一个函数或方法只执行一项任务的做法被称为保持纯函数。这种编码实践来自于函数式编程的概念。如果你想了解更多,我推荐阅读《So You Want to be a Functional Programmer series[4]》。
代码:

// Examples of pure functionsfunction subtract(x, y) { return x - y; }function multiply(x, y) { return x * y; }// Double numbers in an arrayfunction doubleArray(array) { return array.map(number => number * 2) }
Copy after login

4.更容易遵循编码模式
不管多么努力地为变量、函数和方法想出有意义的名字,代码仍然不可能完全清晰易懂,还有一些思路需要进行解释。问题可能不是代码很难理解或使用,相反,其他人可能不理解为什么要实现这个函数或方法,或者为什么要以特定的方式创建它。意思是,创建函数或方法的意图还不清楚。

有时可能不得不采用非传统的方法来解决问题,因为没有足够的时间来想出更好的解决方案,这也很难用代码来解释。所以,通过代码注释可以帮助解决这个问题,也可以帮助我们向其他人解释为什么写了这个方法,为什么要用这种特定的方式来写,那么其他人就不必猜测这些方法或函数的用途了。

更重要的是,当我们使用注来解释代码后,其他人可能会找到一个更好的方法来解决这个问题并改进代码。这是有可能的,因为他们知道问题是什么,以及期望的结果是什么。如果不知道这些信息,其他人就很难创建更好的解决方案,或者他们可能不会去尝试,因为他们认为没有必要去修改创建者自己的想法。

因此,每当自己决定使用一些快速修复或非传统的方法时,要用注释来解释为什么这么做。最好是用一两行注释来解释,而不用别人来猜测。

That is, we should only use comments when necessary and not explain poor code. Writing endless comments will not help transform bad code into clean code. If the code is bad, the problem should be solved by improving the code, not by adding some instructions on how to use it. Writing clean code is more important.

5. Maintain coding style consistency
When we have a specific coding method or style that we like, we will always use it everywhere. But using different coding styles in different projects is not a good idea, and it is impossible to go back to the previous code naturally, so it still takes some time to understand the coding style used in the project.

The best way is to choose a coding method and then stick to it in all projects. That way it will be easier to go back to the old code. Of course, trying new ways of coding is a good thing and helps us find better ways to do our jobs. But it's better to try different coding styles on different lab projects or exercises rather than on the main project.

In addition, when we decide to do some experiments, we should try it multiple times and take the time to do it thoroughly. You should only implement it if you are truly convinced that you like it and are comfortable with it. And when you decide to do this, it's best to apply it to all projects. Yes, it takes time, and it also forces us to think correctly.

6. Check your code

This is the last tip. It’s not just about writing clean code, but there’s also the final piece of work that needs to be done, which is maintaining clean code. We should check the code regularly and try to improve it. Otherwise, if our old code is not reviewed and updated, it will quickly become outdated, just like our devices. If you want to keep your code in tip-top shape, you need to update them regularly.

The same is true for code you use every day. The code will become more complex and confusing, so this should be avoided and the code should be kept clean. The only way to achieve this is to review our code regularly. In other words, we need to keep it. For projects that you no longer care about in the future, this may not be necessary, but for others, maintaining the code is part of the job.

Some Thoughts on Writing Clean Code

The six practices discussed today may not be the most impactful, and they may not be the most important, but these are the ones experienced developers use most often. mentioned, which is why I chose them. I hope these practices or tips help you start writing clean code. Now, as with all things, the most important thing is to get started. So, pick at least one tip and give it a try.

The above is the detailed content of 6 tips for writing good, clean code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!