It is an art to write excellent program code. If you want to do so, you must form good programming habits at the beginning. Good programming habits not only help the early design of the project (such as modularity), but also make the code you write easier to understand, so that the maintenance of the code is easier and more labor-saving. Bad programming habits will cause code bugs and make maintenance work difficult in the future.
This article takes PHP as an example, introduces some good programming habits, hoping to help you.
1. Planning code structure
2. Unified coding style
Good PHP code should have a unified style. For example, making unified naming rules for variables and functions, making unified access standards for circular tasks (such as database access and error handling), or keeping regular code indentation can make it easier for others to read code.
Good PHP code should be portable. Programmers should learn to use the existing features of PHP (such as magic quotes and short tags), understand the product requirements, adapt to the characteristics of PHP, and ensure that the PHP code written is portable and cross platform.
4. Code security
Good PHP code should be secure. PHP5 has excellent features and flexibility, but the security of applications is often in the hands of programmers. As a professional PHP developer, we should have some in-depth understanding of security vulnerabilities. Common security vulnerabilities include cross site script attack (XSS), Cross Site Request Forgery (CSRF), code injection vulnerability and character encoding vulnerability. Using specific functions and functions in PHP (such as MySQL [real] escape [string, etc.) can help programmers write safe code.
5. Add notes
Code annotation is an important part of code, which explains the purpose of function running. This kind of annotation will provide very useful help in the future maintenance of code.
6. Avoid shorthand
A complete start tag should be used, and shorthand start tags are not recommended.
7. Replace double quotation marks with single quotation marks
Because PHP searches for variables in double quotation marks, programmers should use single quotation marks to reference strings in order to avoid the performance impact of this search.
8. Escape output
The ENT [quotes] parameter should be used in the htmlspecialchars function to ensure that single quotes (‘) can also be escaped. Although there is no requirement to do so, it is a good habit.
9. Comma separated string output
String connector (.) can pass a single string to echo statement for output. Compared with it, comma can output strings separately in echo statement, which is a performance improvement for PHP.
10. Check transfer value before output
You should remember to check the pass through value of $_get [‘query ‘] before output. Use the isset function or empty function to check if the variable value is empty.