Five good habits of PHP programming

Source: Internet
Author: User

Generally, developers are 10% less efficient than excellent developers ~ 20%. Excellent developers are more efficient because they have rich experience and good programming habits. Poor programming habits will affect efficiency. This article demonstrates some good programming habits to help you become a better programmer.

These good programming habits not only improve efficiency, but also allow you to write code that is easy to maintain throughout the application lifecycle. The compiled code may require a lot of maintenance; application maintenance is a huge expense. Developing good programming habits can improve the design quality (such as modularization), so that the code is easier to understand. Therefore, maintenance is easier and maintenance costs are also reduced.

Poor programming habits may cause code defects, making it difficult to maintain and modify, and may introduce other defects during modification. Five good programming habits can help PHP code avoid these defects:

◆ Use a good name.

◆ Smaller part.

◆ Add comments to the code.

◆ Handle error conditions.

◆ Do not use copy and paste.

The following describes these habits in detail:

Use good naming

Good naming is the most important programming habit, because a descriptive name makes the code easier to read and understand. Whether the code is easy to understand depends on whether it can be maintained in the future. Even if the code is not annotated, it is easy to understand and can be easily changed in the future. The goal of this habit is to make your code as easy to read and understand as a book.

Bad habits: vague or meaningless names

The code in Listing 1 contains too short variable names and unidentifiable acronyms, and the method name cannot reflect the function of the method. If the method name gives people the feeling that it should do this thing, but in reality it does another thing, it will bring serious problems because it will mislead people.

Listing 1. Bad habits: vague or meaningless names

<? Php

Function getNBDay ($ d ){
Switch ($ d ){
Case 5:
Case 6:
Case 7:
Return 1;
Default:
Return ($ d + 1 );
}
}

$ Day = 5;

$ NextDay = getNBDay ($ day );

Echo ("Next day is:". $ nextDay. "n ");

?>


Good habits: descriptive and concise names

The code in Listing 2 demonstrates good programming habits. The new method name is descriptive and reflects the purpose of the method. Similarly, the changed variable name is more descriptive. The only variable to keep the shortest is $ I. In this list, it is a circular variable. Although many people do not agree to use too short names, it is acceptable (or even good) to use them in loop variables because it clearly indicates the functions of the Code.

Listing 2. Good habits: descriptive and concise names

<? Php
Define (MONDAY, 1 );
Define (TUESDAY, 2 );
Define (WEDNESDAY, 3 );
Define (THURSDAY, 4 );
Define (FRIDAY, 5 );
Define (SATURDAY, 6 );
Define (SUNDAY, 7 );
/*
*
* @ Param $ dayOfWeek
* @ Return int Day of week, with 1 being Monday and so on.
*/
Function findNextBusinessDay ($ dayOfWeek ){
$ NextBusinessDay = $ dayOfWeek;
Switch ($ dayOfWeek ){
Case FRIDAY:
Case SATURDAY:
Case SUNDAY:
$ NextBusinessDay = MONDAY;
Break;
Default:
$ NextBusinessDay + = 1;
Break;
}
Return $ nextBusinessDay;
}
$ Day = FRIDAY;
$ NextBusDay = findNextBusinessDay ($ day );
Echo ("Next day is:". $ nextBusDay. "n ");
?>


We encourage you to split a large condition into a method and use the naming method that can describe the condition. This technique can improve the readability of the code and embody conditions so that the code can be extracted or reused. If conditions change, the update method is also easy. Because a method has a meaningful name, it can reflect the purpose of the code and make the code easier to read.

Into smaller parts

Focus on solving a problem and continue programming. This will make it easier for you. To solve an urgent problem, continuing programming will make the function grow longer and longer. In the long run, this is not a problem, but you should remember to refactor it into a smaller part.

Refactoring is a good idea, but you should develop code with shorter and more concentrated functions. The short method can be read once in a window and is easy to understand. If the method is too long to be read once in a window, it becomes difficult to understand, because you cannot quickly understand the entire idea from start to end.

When constructing a method, you should develop this habit so that each method can accomplish only one thing. This is a good habit, because: First, if a method completes only one thing, it is easier to reuse; second, this method is easy to test; third, this method is easy to understand and change.

Bad habits: methods that are too long (to accomplish many things)

Listing 3 shows a very long function, which has many problems. It does many things, so it is not compact enough. It is not easy to read, debug, and test. It involves traversing a file, building a list, assigning values to each object, and executing computation.

Listing 3. Bad habits: Long Functions

<? Php

Function writeRssFeed ($ user)
{
// Get the DB connection information


// Look up the users preferences...
$ Link = mysql_connect (mysql_host, mysql_user, mysql_password)
OR die (mysql_error ());

// Query
$ PerfsQuery = sprintf ("SELECT max_stories FROM user_perfs WHERE user = % s ",
Mysql_real_escape_string ($ user ));

$ Result = mysql_query ($ query, $ link );

$ Max_stories = 25; // default it to 25;

If ($ row = mysql_fetch_assoc ($ result )){
$ Max_stories = $ row [max_stories];
}

// Go get my data
$ PerfsQuery = sprintf ("SELECT * FROM stories WHERE post_date = % s ",
Mysql_real_escape_string ());

$ Result = mysql_query ($ query, $ link );


$ Feed = "<rss version =" 2.0 "> ".
"<Channel> ".
"<Title> My Great Feed </title> ".
"<Link> http://www.example.com/feed.xml </link> ".
"<Description> The best feed in the world </description> ".
"<Language> en-us </language> ".
"<PubDate> Tue, 20 Oct 2008 10:00:00 GMT </pubDate> ".
"<LastBuildDate> Tue, 20 Oct 2008 10:00:00 GMT </lastBuildDate> ".
"<Docs> http://www.example.com/rss </docs> ".
"<Generator> MyFeed Generator </generator> ".
"<ManagingEditor> editor@example.com </managingEditor> ".
"<WebMaster> webmaster@example.com </webMaster> ".
"<Ttl> 5 </ttl> ";

// Build the feed...
While ($ row = mysql_fetch_assoc ($ result )){
$ Title = $ row [title];
$ Link = $ row [link];
$ Description = $ row [descrip

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.