当前位置:网站首页>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
边栏推荐
- 【高老师软件需求分析】20级云班课习题答案合集
- 信息安全-威胁检测-flink广播流BroadcastState双流合并应用在过滤安全日志
- Ball Dropping
- Essai de pénétration (1) - - outils nécessaires, navigation
- 【练习-6】(PTA)分而治之
- Nodejs+vue online fresh flower shop sales information system express+mysql
- [analysis of teacher Gao's software needs] collection of exercises and answers for level 20 cloud class
- CEP used by Flink
- Interval sum ----- discretization
- Penetration test (3) -- Metasploit framework (MSF)
猜你喜欢
【高老师UML软件建模基础】20级云班课习题答案合集
Vs2019 initial use
D - Function(HDU - 6546)女生赛
Gartner: five suggestions on best practices for zero trust network access
渗透测试 ( 8 ) --- Burp Suite Pro 官方文档
信息安全-安全编排自动化与响应 (SOAR) 技术解析
VS2019初步使用
1010 things that college students majoring in it must do before graduation
X-Forwarded-For详解、如何获取到客户端IP
渗透测试 ( 1 ) --- 必备 工具、导航
随机推荐
【练习-8】(Uva 246)10-20-30==模拟
信息安全-威胁检测-NAT日志接入威胁检测平台详细设计
[teacher Gao UML software modeling foundation] collection of exercises and answers for level 20 cloud class
Opencv learning log 31 -- background difference
C language is the watershed between low-level and high-level
Opencv learning log 12 binarization of Otsu method
China potato slicer market trend report, technical dynamic innovation and market forecast
[exercise-6] (PTA) divide and conquer
STM32 learning record: LED light flashes (register version)
Research Report on shell heater industry - market status analysis and development prospect forecast
【练习-2】(Uva 712) S-Trees (S树)
Opencv learning log 19 skin grinding
HDU - 6024 building shops (girls' competition)
Opencv learning log 16 paperclip count
mysql导入数据库报错 [Err] 1273 – Unknown collation: ‘utf8mb4_0900_ai_ci’
Penetration testing (5) -- a collection of practical skills of scanning King nmap and penetration testing tools
China earth moving machinery market trend report, technical dynamic innovation and market forecast
Determine the Photo Position
Opencv learning log 15 count the number of solder joints and output
Interesting drink