当前位置:网站首页>What is the difficulty of programming?
What is the difficulty of programming?
2022-07-06 16:06:00 【Programming fish 66】
It's easy to write code , It's not easy to write good code .
As a developer , What we need to do is not only to be able to use a programming language and implement a software or project .
As a developer , Look at a project from a higher perspective , Through some good development habits , It can make the written code easier to understand 、 It's easier to expand , It can also be more versatile .
Although developing these good habits requires some learning and understanding costs in the early stage , But once applied to the actual project development , In subsequent functional iterations 、 In the process of adding a scene , Will reduce refactoring 、 The pain of repeating the wheel .
So what is good code ?
I think good code has the following characteristics :
- Readability
- The structural design is elegant
- Easy to understand , Follow the single responsibility principle (SRP)
- Easy to expand and modify
- Experience comprehensive validation and test cases
In order to write good code , Meet these requirements , I have been sticking to some habits these years , today , Let's share .
1. Use meaningful names
Naming is very fundamental in the development process 、 A very common task , It also determines the simplicity of the code 、 The core of readability .
In the process of programming development , Variable 、 function 、 class 、 Parameters 、 modular 、 package 、 Directory etc. , Many places will involve naming .
therefore , It's like naming people , Naming in the development process is also crucial , It can enable us or other readers to obtain valuable information in the shortest time .
I have always insisted in the naming process 3 Principles : What does it do ? Why does it exist ? And how it's used ?
Here's an example :
int b; // Number of users .
In the example above , You need to give a comment along with the variable name , This is not a feature of good code .
I saw an article before : The more comments, the better ?
I think the answer is no , Clear code structure and meaningful naming , Make the reader understand its function at a glance 、 effect , It is superfluous and meaningless to add comments in this way .
however , In the above example code , It's hard to tell what it really wants from its name , therefore , You have to add notes .
As mentioned above 3 Principles , We can explain its function and purpose in variable naming :
int number_of_users
Then it looks , The code will be much simpler , And it's easier for you and other readers to read .
Need to add a little , Although it requires meaningful naming , But there is no need to translate the meaning to be expressed into English word by word , This will be more cumbersome , Try to limit your name to three or four words that will do .
2. Principle of single responsibility (SRP)
In any programming language , class 、 Functions or methods are good ways to organize your code , So when writing code , In particular, we need to pay attention to how to write a function that can convey its intention .
Most beginners make such mistakes , They write functions that can handle almost everything ( Perform multiple tasks ).
This makes the code even more confusing for developers , And before they need to fix some bug Or cause more trouble when looking for some code .
therefore , Writing functions 、 Class , I always insist 2 Principles :
- Try to be as concise as possible
- Do one thing , And do well
The above two points clearly mention , Functions should follow the single responsibility principle . This means that it should not have nested structures , Nor should there be more than two indent levels . Following this technique makes the code more readable .
in addition , Make sure that the function should not have more than three arguments . Passing more than three parameters can confuse the code , If there are any questions , It's also hard to debug .
Besides , As I said before , Note the function name . Use a descriptive name for your function , It should clearly state what functions do :
function subtract(x, y) {
return x - y;
}
In the example above , The function name clearly indicates that its purpose is to subtract two numbers , And it has only two parameters .
3. Avoid unnecessary comments
This was mentioned earlier , The more comments, the better ?
Many bloggers will repeatedly emphasize the importance of annotations , Try to write notes anyway .
You bet , The necessary comments are helpful in interpreting the code , But it also requires more maintenance of the code , And as the code changes , The notes also need to be changed accordingly , Otherwise, more ambiguities will be introduced .
Besides , If the name can clearly explain a parameter 、 The function of a function , So it doesn't make sense to add more comments .
4. Write readable code for people
A lot of people , Especially beginners , You make such mistakes when writing code : They put everything on one line , Without leaving appropriate white space in the code 、 Indent or wrap .
This makes their code confusing , Difficult to maintain .
especially , When other developers try to read and understand confusing code , This wastes their time .
So always pay attention to the format of your code , Writing code is not just about getting results without reporting errors , It also needs to be better understood .
and , When you go back to your code in a few days and make some changes , You will also save your time and energy .
So make sure your code is properly indented 、 Space and line breaks , To make it readable to others :
// Bad code
class CarouselRightArrow extends Component{render(){return ( <a href="#" className="carousel__arrow carousel__arrow--left" onClick={this.props.onClick}> <span className="fa fa-2x fa-angle-left"/> </a> );}};
// Good code
class CarouselRightArrow extends Component {
render() {
return (
<a
href="#"
className="carousel__arrow carousel__arrow--left"
onClick={this.props.onClick}
>
<span className="fa fa-2x fa-angle-left" />
</a>
);
}
};
5. To write unit testing
Writing unit tests is very important in development , It makes your code clean 、 Flexible and maintainable , It becomes easier to modify the code and reduce errors .
In software development , There is a process called test driven development (TDD), In the process , Requirements are translated into specific test cases , Then the software needs to be constantly improved to pass new tests .
such , Our code can have more stability and robustness .
6. Be cautious about dependencies
In software development , You need to be careful about your dependencies .
If possible , Dependencies should always be a single direction .
Take an example of one-way dependency .
Suppose we have a kitchen class , It depends on the dishwasher class . As long as the dishwasher doesn't depend on the kitchen class , So that's one Single direction Dependency of . The kitchen class is just using the dishwasher , But the dishwasher doesn't care what scenario to use .
However , There can't always be one-way dependencies , But we should have as many one-way dependencies as possible . When dependencies move in multiple directions , Things will get more complicated . In a two-way dependency , Both entities depend on each other , So they must exist together , Although they are separate . When the dependencies of some systems do not form a single direction , It's hard to update , Difficult to decouple .
therefore , Always manage your dependencies carefully .
7. Keep the project in order
This is a very common problem in software development , We have added and deleted many files or directories in the project , Sometimes it gets very complicated , Make it impossible for other developers to understand the project and work on it .
Of course , We can't design a perfect one on the first day Folder Or file organization , But later , When your project gets bigger , You need to pay attention to the folder 、 Files and directories Organizational structure .
A well structured folder and file makes everything clear , Understand a complete project , It becomes easier to search for specific folders and make changes in them .
8. Avoid unnecessary nesting
Nesting in code is something we often do , Although nesting itself is not a problem , But sometimes it makes the code harder to read .
One way to help avoid this is to use "Return Early " Design patterns .
It allows us to if
Statement as a protection clause , Check for errors and return... Before executing the next step of the code .
It helps avoid use if/else And unnecessary nesting , for instance :
Before the change
function deleteItem(item) {
if (item != null) {
console.log("Deleting item");
item.delete();
}
}
After modification
function deleteItem(item) {
if (item == null) return;
console.log("Deleting item");
item.delete();
}
This is something that I have insisted on for a long time in the process of writing code 8 A habit , Summed up for a long time , I hope that's helpful !
If it feels good , Just point a favor to support it !
resources & More in-depth readings :
Open the mysterious channel to get information, click the link to join the group chat 【C Language /C++ Programming learning base 】:828339809
边栏推荐
- Information security - security professional name | CVE | rce | POC | Vul | 0day
- China's peripheral catheter market trend report, technological innovation and market forecast
- Nodejs+vue online fresh flower shop sales information system express+mysql
- 【练习-11】4 Values whose Sum is 0(和为0的4个值)
- 差分(一维,二维,三维) 蓝桥杯三体攻击
- Research Report of exterior wall insulation system (ewis) industry - market status analysis and development prospect prediction
- 【练习-7】(Uva 10976)Fractions Again?!(分数拆分)
- JS调用摄像头
- The concept of C language array
- 入门C语言基础问答
猜你喜欢
Pyside6 signal, slot
Borg Maze (BFS+最小生成树)(解题报告)
STM32 how to use stlink download program: light LED running light (Library version)
信息安全-威胁检测-flink广播流BroadcastState双流合并应用在过滤安全日志
信息安全-威胁检测-NAT日志接入威胁检测平台详细设计
Nodejs+vue online fresh flower shop sales information system express+mysql
渗透测试 ( 1 ) --- 必备 工具、导航
【高老师UML软件建模基础】20级云班课习题答案合集
信息安全-威胁检测引擎-常见规则引擎底座性能比较
mysql导入数据库报错 [Err] 1273 – Unknown collation: ‘utf8mb4_0900_ai_ci’
随机推荐
China exterior wall cladding (EWC) market trend report, technical dynamic innovation and market forecast
Borg maze (bfs+ minimum spanning tree) (problem solving report)
0 - 1 problème de sac à dos (1)
Borg Maze (BFS+最小生成树)(解题报告)
[exercise-7] (UVA 10976) fractions again?! (fraction split)
入门C语言基础问答
frida hook so层、protobuf 数据解析
[teacher Gao UML software modeling foundation] collection of exercises and answers for level 20 cloud class
Perform general operations on iptables
Ball Dropping
Information security - threat detection - detailed design of NAT log access threat detection platform
渗透测试 ( 7 ) --- 漏洞扫描工具 Nessus
B - 代码派对(女生赛)
差分(一维,二维,三维) 蓝桥杯三体攻击
信息安全-史诗级漏洞Log4j的漏洞机理和防范措施
Find 3-friendly Integers
Opencv learning log 30 -- histogram equalization
[exercise-1] (UVA 673) parentheses balance/ balanced brackets (stack)
【练习-5】(Uva 839)Not so Mobile(天平)
X-Forwarded-For详解、如何获取到客户端IP