Code with a strong readability, can help you debug the program, not to live too tired.

Code readability is a common problem in computer programming. This is one of the first things we learn as developers. This article details some of the most important best practices for writing highly readable code.

1 – Notes and documentation

IDE (Integrated Development Environmnet) has been around for a long time over the years. Commenting code with IDE is much easier than ever. There are specific annotation standards that allow ides and other tools to do annotation differently.

Here’s an example:

The comments I added here before the function definition can be displayed when using the function, even in other files.

Here is another example of calling a function from a third-party library:

In these examples, the annotation (or document) type is phpDoc-based and the IDE used is Aptana.


The book

Other Translations (1)

2 – Keep consistent indentation

Assume that you already know the code needs to be indent. It’s worth noting, though, that it’s best to keep the indentation style consistent.

There are many ways to indent code, but here are the two most common:

Style 1:

function foo() {
    if($maybe){
        do_it_now();
        again();
    } else{
        abort_mission();
    }
    finalize();
}Copy the code

Style 2:

function foo(){  
if($maybe) {  
 do_it_now();
        again();
    }else{  
 abort_mission();
    }
    finalize();
}Copy the code

I used to use style #2, but recently changed to #1. But the problem is simply a matter of preference. There is no “best” style for everyone to follow. In fact, the best style is consistent style. If you are part of a team, or if you are contributing code to a project, you should follow the style that is being used in the project.

There is not always a clear distinction between indent styles. Sometimes, different rules can lead to confusion. For example, in the PEAR coding standard, the leading curly brace “{” is on the same line as the control structure, but line breaks are required in function definitions.

The PEAR style:

Function foo(){// put on the next line if($maybe){// put on the same line do_it_now(); again(); }else{ abort_mission(); } finalize(); }Copy the code

Also, notice that the indent is 4 Spaces instead of tabs.

Here are examples of different indentation styles in Wikipedia.


The book

3 – Avoid obvious comments

The commented code is great; However, comments are redundant if they are simply repetitions. Look at this example:

$country_code = get_country_code($_SERVER['REMOTE_ADDR']); If ($country_code == 'US'){echo form_input_state(); }Copy the code

If the text is obvious, there’s really no need to write it again in comments.

If you must include some comments in your code, you can combine them on one line:

$country_code = get_COUNTRY_code ($_SERVER['REMOTE_ADDR']); if ($country_code == 'US'){ echo form_input_state(); }Copy the code

4 – Code grouping

Some tasks can take more than a few lines of code, so it’s best to break them up into separate code segments and add blank lines between them.

Here is a simple example:

// 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');Copy the code

Adding comments at the beginning of each piece of code enhances visual separation.


The book

5 – Keep consistent naming conventions

PHP itself sometimes does not follow a consistent naming convention:

  • strpos() vs. str_split()

  • imagetypes() vs. image_type_to_extension()

First, names should have word boundaries. Here are two popular options:

  • CamelCase: Capitalize the first letter of every word except the first.

  • Underscores: Underscores are used to separate words, such as mysql_real_escape_string().

This is similar to the situation I mentioned earlier when using different indentation styles. If a convention is already in use in your project, you should follow it. In addition, some language platforms tend to have a specific naming convention. In Java, for example, most code uses the camel name style, while most PHP programmers use the underline style.

These networks can also be mixed. Some developers like to use the underline style for procedure functions and classes, but use the hump style for class methods:

class Foo_Bar {
    publicfunctionsomeDummyMethod(){
}Copy the code

Again, there is no “best” style, just be consistent.


The book

6 – DRY principle

DRY stands for Don’t Repeat Yourself. Also known as DIE: Duplication is unacceptable.

The principle provides that:

“Every knowledge must have a unique, unambiguous, authoritative representation within a system.”

The goal of most applications (or general-purpose computers) is to automate repetitive tasks. This principle should be retained in all code, including Web applications. The same code should not be repeated over and over again.

For example, most Web applications consist of many pages. These pages are likely to contain common elements. Headings and footers are usually the best proof. It’s not a good idea to make a copy of these headers and footers on each page. Jeffrey Way explains how to create templates in CodeIgniter.

$this->load->view('includes/header');   
$this->load->view($main_content);   
$this->load->view('includes/footer');Copy the code


Tocy

7 – Avoid deep nesting

Too many nesting layers can make code difficult to read and track

functiondo_stuff(){
// ...
if (is_writable($folder)){
    if ($fp = fopen($file_path, 'w')){
        if ($stuff = get_some_stuff()){
            if (fwrite($fp, $stuff)){
// ...
   }
      else
   {
    returnfalse;
   }
  }
  else
{Copy the code

To improve readability, code is often modified to reduce nesting levels:

functiondo_stuff(){ // ... if (! is_writable($folder)){ returnfalse; } if (! $fp = fopen($file_path, 'w')){ returnfalse; } if (! $stuff = get_some_stuff()){ returnfalse; } if (fwrite($fp, $stuff)){ // ... } else { returnfalse; }}Copy the code

8 – Limit line length

The human eye feels more comfortable reading long, narrow columns of text, which is why newspaper articles look like this:

It is good practice to avoid excessively long lines of code

//bad
$my_email->set_from('[email protected]')->add_to('[email protected]')->set_subject('Methods Chained')->set_body('Some long message')->send();   
// good
$my_email   
->set_from('[email protected]')    
  ->add_to('[email protected]')    
  ->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 = 
                                '123' ";   
// 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 =  '123' ";Copy the code

Of course, if someone, like a Vim user, wants to read your code in a terminal window, it’s best to limit the line length to about 80 characters.


baiyangcao

9 – Organization of files and folders

Technically, you can code an entire application in a single file. However, this can be a nightmare to read and maintain.

In my first programming project, I learned how to create “include files.” However, I haven’t had any contact with remote organizations. I created an “inc” folder with two files: db.php and functions.php. As the application expands, functions files become large and unmaintainable.

One of the best ways to do this is to use a framework or mimic its folder structure. Here is CodeIgniter’s code layout:


Tocy

10 – Consistent temporary variable naming

In general, variables should be descriptive and contain one or more words. However, this does not necessarily apply to temporary variables. They can be as short as a single character.

It is a good practice to use consistent names for temporary variables that have the same function. Here are a few examples I often use in code:

// $i for loop countersfor
($i= 0; $i< 100; $i++) {       
  // $j for the nested loop counters    
  for($j= 0; $j< 100; $j++) {       
  }
}   
// $ret for return variables
functionfoo() {    
 $ret['bar'] = get_bar();    
 $ret['stuff'] = get_stuff();       
 return$ret;
}   
// $k and $v in foreachforeach
($some_arrayas$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');Copy the code

Explore the necessity of TDM for speed and quality in agile, DevOps, and continuous delivery. Work hand in hand with CA technology.


Tocy