[Reprint] 15 best practices for writing super-readable code

Source: Internet
Author: User
Tags pear php foreach zend framework

Translation: http://net.tutsplus.com/tutorials/html-css-techniques/top-15-best-practices-for-writing-super-readable-code/

Jiang Yujie (reprinted please indicate the source-http://blog.csdn.net/hfahe)

Twice in January, we review the favorite articles in Nettuts's history.
Code readability is a common topic in the computer programming world. It is the first thing we learn as developers. This article describes the fifteen most important best practices for writing readable code.

--------------------------------------------------------------------------------

1-annotation and document integration development environment IDE has gone a long way over the past few years. It makes the annotation code more useful than before. Annotations written according to specific standards allow the IDE and other tools to use them in different ways.
Consider the following example:

The comments I added in the function definition can be seen at the place where it is called, even in other files.
Here is another example of calling a function from a third-party Library:

In these special examples, the annotation (or document) type is based on PHPDoc, And the IDE is Aptana.

--------------------------------------------------------------------------------

2-consistent layout
I suppose you already know that you must indent your code. However, it is still a good idea to keep the typographical style consistent.
There are more than one way to typeset code.
First: view plaincopy to clipboardprint?
01. function foo (){
02. if ($ maybe ){
03. do_it_now ();
04. again ();
05.} else {
06. abort_mission ();
07 .}
08. finalize ();
09 .}
Function foo (){
If ($ maybe ){
Do_it_now ();
Again ();
} Else {
Abort_mission ();
}
Finalize ();
}

Type 2: view plaincopy to clipboardprint?
01. function foo ()
02 .{
03. if ($ maybe)
04 .{
05. do_it_now ();
06. again ();
07 .}
08. else
09 .{
10. abort_mission ();
11 .}
12. finalize ();
13 .}
Function foo ()
{
If ($ maybe)
{
Do_it_now ();
Again ();
}
Else
{
Abort_mission ();
}
Finalize ();
}

Third: view plaincopy to clipboardprint?
01. function foo ()
02. {if ($ maybe)
03. {do_it_now ();
04. again ();
05 .}
06. else
07. {abort_mission ();
08 .}
09. finalize ();
10 .}
Function foo ()
{If ($ maybe)
{Do_it_now ();
Again ();
}
Else
{Abort_mission ();
}
Finalize ();
}

I used the second style, but recently changed it to the first one. However, this only represents a preference. No one has to follow the "best" style here. In fact, the best style is consistent style. If you are part of a group or you are contributing code to a project, you must follow the style used before the project.
The typographical style is not totally different from the other one. Sometimes they are mixed with different rules. For example, according to the PEAR encoding standard, the front arc "{" and the control structure are on the same line, but are placed on the second line after the function definition.
PEAR style:
View plaincopy to clipboardprint?
01. function foo ()
02. {// placed on the next line
03. if ($ maybe) {// placed on the same line
04. do_it_now ();
05. again ();
06.} else {
07. abort_mission ();
08 .}
09. finalize ();
10 .}
Function foo ()
{// Placed on the next line
If ($ maybe) {// placed on the same line
Do_it_now ();
Again ();
} Else {
Abort_mission ();
}
Finalize ();
}

At the same time, note that they use four spaces instead of tabs for indentation.
Here is a Wikipedia article with many examples of different typographical styles.

--------------------------------------------------------------------------------

3-to avoid obvious comments, adding comments to the code is quite effective. However, it may be too much or just Redundant text. For example:
View plaincopy to clipboardprint?
01. // get the country code
02. $ country_code = get_country_code ($ _ SERVER ['remote _ ADDR ']);
03. // if country code is US
04. if ($ country_code = 'us '){
05. // display the form input for state
06. echo form_input_state ();
07 .}
// Get the country code
$ Country_code = get_country_code ($ _ SERVER ['remote _ ADDR ']);
// If country code is US
If ($ country_code = 'us '){
// Display the form input for state
Echo form_input_state ();
}

If the comments are obvious, they do not improve work efficiency. If you need to comment out these codes, you can simply merge them into one line:
View plaincopy to clipboardprint?
01. // display state selection for US users
02. $ country_code = get_country_code ($ _ SERVER ['remote _ ADDR ']);
03. if ($ country_code = 'us '){
04. echo form_input_state ();
05 .}
// Display state selection for US users
$ Country_code = get_country_code ($ _ SERVER ['remote _ ADDR ']);
If ($ country_code = 'us '){
Echo form_input_state ();
}

--------------------------------------------------------------------------------

4-multiple lines of code are required for most tasks identified by code groups. It is a good idea to use some blank spaces to separate the code of these tasks into several segments.

This is a simple example:
View plaincopy to clipboardprint?
01. // get list of forums
02. $ forums = array ();
03. $ r = mysql_query ("SELECT id, name, description FROM forums ");
04. while ($ d = mysql_fetch_assoc ($ r )){
05. $ forums [] = $ d;
06 .}
07. // load the templates
08. load_template ('header ');
09. load_template ('Forum _ list', $ forums );
10. load_template ('footer ');
// Get list of forums
$ Forums = array ();
$ R = mysql_query ("SELECT id, name, description FROM forums ");
While ($ d = mysql_fetch_assoc ($ r )){
$ Forums [] = $ d;
}
// Load the templates
Load_template ('header ');
Load_template ('Forum _ list', $ forums );
Load_template ('footer ');

Adding annotations before each section also enhances visual separation.

--------------------------------------------------------------------------------

5-naming consistency
PHP sometimes has a major problem in terms of compliance with naming consistency:
• Strops () and str_split ()
• Imagetypes () and image_type_to_extension ()
First, these names must have word boundaries. There are two popular options:
• Camel naming: In addition to the first word, the first character of each word is capitalized.
• Underline naming: underlines are used between words, for example, mysql_real_escape_string ().
As I mentioned earlier, using different naming options will create a scenario similar to the typographical style. If an existing project follows a definite habit, you must follow it. In addition, some language platforms tend to use specific naming rules. For example, in Java, most Code uses the camel naming method; in PHP, most use the underline naming method.
They can also be mixed. Some developers like to name program functions and classes with underscores, but use camels for class method names.
View plaincopy to clipboardprint?
01. class Foo_Bar {
02. public function someDummyMethod (){
03 .}
04 .}
05. function procedural_function_name (){
06 .}
Class Foo_Bar {
Public function someDummyMethod (){
}
}
Function procedural_function_name (){
}

Therefore, there is no obvious "best" style, and you only need to keep it consistent.

--------------------------------------------------------------------------------

6-DRY principle: Do not repeat yourself. Also known as DIE: repetition is a devil.
This principle stipulates:
"Each piece of knowledge in a system must have a single, clear, and authoritative expression ."
Most applications (or computers) aim to automate repetitive tasks. This principle should be maintained in all code, even in Web programs. The same part of the Code should not be repeated multiple times.
For example, most Web programs consist of many pages. These pages may contain the same elements. The page header and footer often meet this condition. It is not a good idea to copy and paste these headers and footer pages to each page. This is the link Jeffrey Way explains how to create a template in CodeIgniter.
View plaincopy to clipboardprint?
01. $ this-> load-> view ('regiondes/header ');
02. $ this-> load-> view ($ main_content );
03. $ this-> load-> view ('shortdes/footer ');
$ This-> load-> view ('regiondes/header ');
$ This-> load-> view ($ main_content );
$ This-> load-> view ('shortdes/footer ');

--------------------------------------------------------------------------------

7-Avoid code reading and tracking difficulties if too many layers of nesting are too deep.
View plaincopy to clipboardprint?
01. function do_stuff (){
02 .//...
03. if (is_writable ($ folder )){
04. if ($ fp = fopen ($ file_path, 'w ')){
05. if ($ stuff = get_some_stuff ()){
06. if (fwrite ($ fp, $ stuff )){
07 .//...
08.} else {
09. return false;
10 .}
11.} else {
12. return false;
13 .}
14.} else {
15. return false;
16 .}
17.} else {
18. return false;
19 .}
20 .}
Function do_stuff (){
//...
If (is_writable ($ folder )){
If ($ fp = fopen ($ file_path, 'w ')){
If ($ stuff = get_some_stuff ()){
If (fwrite ($ fp, $ stuff )){
//...
} Else {
Return false;
}
} Else {
Return false;
}
} Else {
Return false;
}
} Else {
Return false;
}
}

For readability, you usually need to modify the code to reduce the number of layers of nesting.
View plaincopy to clipboardprint?
01. function do_stuff (){
02 .//...
03. if (! Is_writable ($ folder )){
04. return false;
05 .}
06. if (! $ Fp = fopen ($ file_path, 'w ')){
07. return false;
08 .}
09. if (! $ Stuff = get_some_stuff ()){
10. return false;
11 .}
12. if (fwrite ($ fp, $ stuff )){
13 .//...
14.} else {
15. return false;
16 .}
17 .}
Function do_stuff (){
//...
If (! Is_writable ($ folder )){
Return false;
}
If (! $ Fp = fopen ($ file_path, 'w ')){
Return false;
}
If (! $ Stuff = get_some_stuff ()){
Return false;
}
If (fwrite ($ fp, $ stuff )){
//...
} Else {
Return false;
}
}

--------------------------------------------------------------------------------

8-Reduce the length of rows our eyes are more comfortable with reading high and narrow text columns. This is why newspaper articles look like the following:

It is a best practice to avoid writing too long code on a line.
View plaincopy to clipboardprint?
01. // bad
02. $ my_email-> set_from ('test @ email.com ')-> add_to ('Programming @ gmail.com')-> set_subject ('Methods chained ') -> set_body ('some long message')-> send ();
03. // good
04. $ my_email
05.-> set_from ('test @ email.com ')
06.-> add_to ('Programming @ gmail.com ')
07.-> set_subject ('Methods chained ')
08.-> set_body ('some long message ')
09.-> send ();
10. // bad
11. $ query = "SELECT id, username, first_name, last_name, status FROM users left join user_posts USING (users. id, user_posts.user_id) WHERE post_id = '2013 '";
12. // good
13. $ query = "SELECT id, username, first_name, last_name, status
14. FROM users
15. left join user_posts USING (users. id, user_posts.user_id)
16. WHERE post_id = '123 '";
// Bad
$ My_email-> set_from ('test @ email.com ')-> add_to ('Programming @ gmail.com')-> set_subject ('Methods chained ') -> set_body ('some long message')-> send ();
// Good
$ My_email
-> Set_from ('test @ email.com ')
-> Add_to ('Programming @ gmail.com ')
-> Set_subject ('Methods chained ')
-> Set_body ('some long message ')
-> Send ();
// Bad
$ Query = "SELECT id, username, first_name, last_name, status FROM users left join user_posts USING (users. id, user_posts.user_id) WHERE post_id = '2013 '";
// Good
$ Query = "SELECT id, username, first_name, last_name, status
FROM users
Left join user_posts USING (users. id, user_posts.user_id)
WHERE post_id = '20140901 '";

At the same time, if anyone wants to read code in a terminal window such as Vim, it is a good idea to limit the length of each line to 80 characters.

--------------------------------------------------------------------------------

9-in terms of code structure, you can write the entire application code in a file. But it is a nightmare for reading and maintenance.
In my first programming project, I knew the meaning of creating an "include file. However, I have not organized it properly. I created a "inc" folder and placed two files: db. php and functions. php. When the program grows, the functions files become larger and difficult to maintain.
One of the best ways is to use a framework or imitate their folder structure. The file structure of CodeIgniter is as follows:

--------------------------------------------------------------------------------

10-The unified temporary variable name is generally, the variable name should be descriptive and contain one or more words. However, this is not necessary for temporary variables. They can be as short as only one single character.
Best Practice: Use a uniform name for temporary variables with the same responsibilities. Here are some examples that I prefer to use in code:
View plaincopy to clipboardprint?
01. // $ I for loop counters
02. for ($ I = 0; I I <100; $ I ++ ){
03. // $ j for the nested loop counters
04. for ($ j = 0; $ j <100; $ j ++ ){
05 .}
06 .}
07. // $ ret for return variables
08. function foo (){
09. $ ret ['bar'] = get_bar ();
10. $ ret ['stuff '] = get_stuff ();
11. return $ ret;
12 .}
13. // $ k and $ v in foreach
14. foreach ($ some_array as $ k => $ v ){
15 .}
16. // $ q, $ r and $ d for mysql
17. $ q = "SELECT * FROM table ";
18. $ r = mysql_query ($ q );
19. while ($ d = mysql_fetch_assocr ($ r )){
20 .}
21. // $ fp for file pointers
22. $ fp = fopen('file.txt ', 'w ');
// $ I for loop counters
For ($ I = 0; I I <100; $ I ++ ){
// $ J for the nested loop counters
For ($ j = 0; $ j <100; $ j ++ ){
}
}
// $ Ret for return variables
Function foo (){
$ Ret ['bar'] = get_bar ();
$ Ret ['stuff '] = get_stuff ();
Return $ ret;
}
// $ K and $ v in foreach
Foreach ($ some_array as $ k => $ v ){
}
// $ Q, $ r and $ d for mysql
$ Q = "SELECT * FROM table ";
$ R = mysql_query ($ q );
While ($ d = mysql_fetch_assocr ($ r )){
}
// $ Fp for file pointers
$ Fp = fopen('file.txt ', 'w ');

--------------------------------------------------------------------------------

11-SQL keyword capital database interaction is a major component of most Web applications. If you are writing SQL queries, try to keep them readable.
Even if SQL keywords and function names are case-insensitive, it is a common practice to distinguish them from table names and column names in uppercase.
View plaincopy to clipboardprint?
01. SELECT id, username FROM user;
02. UPDATE user SET last_login = NOW ()
03. WHERE id = '123'
04. SELECT id, username FROM user u
05. left join user_address ua ON (u. id = ua. user_id)
06. WHERE ua. state = 'ny'
07. group by u. id
08. order by u. username
09. LIMIT 0, 20
SELECT id, username FROM user;
UPDATE user SET last_login = NOW ()
WHERE id = '000000'
SELECT id, username FROM user u
Left join user_address ua ON (u. id = ua. user_id)
WHERE ua. state = 'ny'
Group by u. id
Order by u. username
LIMIT 0, 20

--------------------------------------------------------------------------------

12-code and data separation is another principle applicable to the vast majority of programming languages in all environments. In Web development, data usually means HTML output.
When PHP was first released many years ago, it was initially seen as a template engine. It is very common to insert some PHP code lines into a huge HTML file. However, over the years, things have changed: websites have become increasingly dynamic and functional. Code is already a large part of Web programs. It is not a good practice to combine them with HTML.
You can apply this principle in your program, or you can use a third-party tool (template engine, framework, or CMS system) or follow their habits.
Popular PHP frameworks:
• CodeIgniter
• Zend Framework
• Cake PHP
• Symfony
Popular template engines:
• Smarty
• Dwoo
• Savant
Popular CMS systems:

• Joomla
• Drupal

--------------------------------------------------------------------------------

13-you can choose not to use a strange template engine to replace the alternative format in the template file with pure inline PHP code. This is not a violation of "data and code separation", but the Inline code is directly related to the output and readable. In this case, you can consider using alternative formats to control the structure.
This is an example:
View plaincopy to clipboardprint?
01. <div class = "user_controls">
02. <? Php if ($ user = Current_User: user ():?>
03. Hello, <em> <? Php echo $ user-> username;?> </Em> <br/>
04. <? Php echo anchor ('logout', 'logout');?>
05. <? Php else:?>
06. <? Php echo anchor ('login', 'login');?> |
07. <? Php echo anchor ('signup', 'Register ');?>
08. <? Php endif;?>
09. </div>
10. 11. <? Php foreach ($ categories as $ category):?>
12. <div class = "category">
13. 14. <? Php foreach ($ category-> Forums as $ forum):?>
15. <div class = "forum">
16. 17. <? Php echo anchor ('forums/'. $ forum-> id, $ forum-> title)?>
18. (<? Php echo $ forum-> Threads-> count ();?> Threads)
19. 20. <div class = "description">
21. <? Php echo $ forum-> description;?>
22. </div>
23. </div>
24. <? Php endforeach;?>
25. </div>
26. <? Php endforeach;?>
<Div class = "user_controls">
<? Php if ($ user = Current_User: user ():?>
Hello, <em> <? Php echo $ user-> username;?> </Em> <br/>
<? Php echo anchor ('logout', 'logout');?>
<? Php else:?>
<? Php echo anchor ('login', 'login');?> |
<? Php echo anchor ('signup', 'Register ');?>
<? Php endif;?>
</Div>
<H1> My Message Board <? Php foreach ($ categories as $ category):?>
<Div class = "category">
<H2> <? Php echo $ category-> title;?> </H2>
<? Php foreach ($ category-> Forums as $ forum):?>
<Div class = "forum">
<H3>
<? Php echo anchor ('forums/'. $ forum-> id, $ forum-> title)?>
(<? Php echo $ forum-> Threads-> count ();?> Threads)
</H3>
<Div class = "description">
<? Php echo $ forum-> description;?>
</Div>
</Div>
<? Php endforeach;?>
</Div>
<? Php endforeach;?>

This avoids many braces. At the same time, the Code looks similar to the HTML structure and layout.

--------------------------------------------------------------------------------

14-object-oriented vs object-oriented programming can help you create Structured code. However, this does not mean that you are completely excluded from procedural programming. In fact, it is great to create a mix of the two.
Description data, usually the data in the database, must use objects.
View plaincopy to clipboardprint?
01. class User {
02. public $ username;
03. public $ first_name;
04. public $ last_name;
05. public $ email;
06. public function _ construct (){
07 .//...
08 .}
09. public function create (){
10 .//...
11 .}
12. public function save (){
13 .//...
14 .}
15. public function delete (){
16 .//...
17 .}
18 .}
Class User {
Public $ username;
Public $ first_name;
Public $ last_name;
Public $ email;
Public function _ construct (){
//...
}
Public function create (){
//...
}
Public function save (){
//...
}
Public function delete (){
//...
}
}

Programmatic methods are often used for specific tasks that can be executed independently.
View plaincopy to clipboardprint?
01. function capitalize ($ string ){
02. $ ret = strtoupper ($ string [0]);
03. $ ret. = strtolower (substr ($ string, 1 ));
04. return $ ret;
05 .}
Function capitalize ($ string ){
$ Ret = strtoupper ($ string [0]);
$ Ret. = strtolower (substr ($ string, 1 ));
Return $ ret;
}

--------------------------------------------------------------------------------

15-reading open-source code open-source projects is built by many developers. These projects must maintain a high degree of code readability so that they can work together as efficiently as possible.
Therefore, it is great to read the source code of these projects to see how these developers work.

--------------------------------------------------------------------------------

16-code refactoring when you "refactor", you can adjust the code without changing the function. You can think of it as "cleaning" to improve code quality and readability.
This does not include fixing bugs or adding new features. You can refactor the code you wrote before, so that you can review the code more readable and reusable after two months. As the saying goes: "early reconstruction, frequent reconstruction".
You can apply any of the above "best practices" about code readability during refactoring. I hope you like this article! What have I forgotten? Please reply to me.

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/hfahe/archive/2011/04/05/6303585.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.