In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
In this issue, the editor will bring you what are the five good habits of PHP programming. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.
Depending on the situation, the average developer is often 10% or 20% less efficient than a good developer. Good developers are more efficient because they have rich experience and good programming habits. Bad programming habits will affect efficiency. This article will help you become a better programmer by showing some good programming habits.
These good programming habits not only improve efficiency, but also allow you to write code that is easy to maintain throughout the life cycle of your application. The written code may require a lot of maintenance; the maintenance of the application is a great expense. Developing good programming habits can improve the quality of the design (such as modularization), making the code easier to understand, making it easier to maintain and reducing maintenance costs.
Bad programming habits can cause code defects, making it difficult to maintain and modify, and are likely to introduce other defects when they are modified. Here are five good programming habits that can help PHP code avoid these defects:
◆ uses a good naming.
The ◆ is divided into smaller parts.
◆ adds comments to the code.
◆ handles error conditions.
Do not use copy and paste in ◆.
These habits are described in more detail below:
Use good naming
Using good naming is the most important programming habit, because descriptive names make 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 uncommented, if it is easy to understand, it will greatly facilitate future changes. The goal of this habit is to make the code you write as easy to read and understand as a book.
Bad habits: vague or meaningless names
The code in listing 1 contains short variable names, illegible acronyms, and method names that do not reflect the functionality of the method. If the method name gives the impression that it should do this thing, but in fact it does something else, it will cause serious problems because it can be misleading.
Listing 1. Bad habits: vague or meaningless names
Good habit: descriptive and concise names
The code in listing 2 shows good programming habits. The new method name is highly illustrative and reflects the use of the method. Similarly, the changed variable name is also more illustrative. The only variable that keeps the shortest is $I, which in this listing is a circular variable. Although many people disapprove of using short names, it is acceptable (and even beneficial) to use in loop variables because it clearly indicates the functionality of the code.
Listing 2. Good habit: descriptive and concise names
Phpdefine ('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 the large condition into a method and then name the method with a name that describes the condition. This technique can improve the readability of the code and specify the conditions so that they can be extracted or even reused. It is also easy to update the method if the conditions change. Because the method has a meaningful name, it reflects the purpose of the code and makes the code easier to read.
Divide into smaller parts
Focus on solving a problem before you continue programming, which will make it easier for you. When solving an urgent problem, if you continue to program, it will make the function longer and longer. This is not a problem in the long run, but remember to go back and ReFactor it into smaller parts.
Refactoring is a good idea, but you should develop shorter, more focused code. Short methods can be seen at once in a window and are easy to understand. If the method is too long to read all at once in a window, it becomes difficult to understand because you can't quickly understand its whole idea from beginning to end.
When building methods, you should get into the habit of getting each method to accomplish only one thing. This habit is good because: first, if a method accomplishes only one thing, it is easier to reuse; second, it is easy to test; and third, it is easy to understand and change.
Bad habits: an overly long method (getting a lot of things done)
Listing 3 shows a long function with a lot of problems. It does a lot of things, so it's not compact enough. It is also not easy to read, debug, and test. What it does include traversing a file, building a list, assigning values to each object, performing calculations, and so on.
Listing 3. Bad habits: overly long functions
". "< 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 ['description']; $date = $row [' date']; $guid = $row ['guid']; $feed. = "< item >"; $feed. = "< title >". $title. "< / title >"; $feed. = "< link >". $link. "< / link >"; $feed. = "< description >". $description. "< / description >"; $feed. = "< pubDate >". $date. "< / pubDate >"; $feed. = "< guid >". $guid. "< / guid >"; $feed. = "< / item >";} $feed. = "< / rss"; / / write the feed out to the server... Echo ($feed);}? >
If you write a few more such methods, maintenance becomes a real problem.
Good habits: an easy-to-manage, functional approach
Listing 4 rewrites the original method to be more compact and readable. In this example, a long method is broken down into several short methods, and each short method is responsible for one thing. Such code is of great benefit to future reuse and testing.
Listing 4. Good habits: an easy-to-manage, functional approach
". "< 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 >";} function createRssFooter () {return "< / channel > < / rss >";} function createRssItem ($title, $link, $desc, $date, $guid) {$item. = "< item >"; $item. = "< title >". $title. "< / title >"; $item. = "< link >". $link. "< / link >"; $item. = "< description >". $description. "< / description >"; $item. = "< pubDate >". $date. "< / pubDate >"; $item. = "< guid >". $guid. "< / guid >"; $item. = "< / item >"; return $item;} function getUserMaxStories ($db_link, $default) {$perfsQuery = sprintf ("SELECT max_stories FROM user_perfs WHERE user='% s'", mysql_real_escape_string ($user)); $result = mysql_query ($perfsQuery, $db_link); $max_stories = $default If ($row = mysql_fetch_assoc ($result)) {$max_stories = $row ['max_stories'];} return $max_stories;} function writeRssFeed ($user) {/ / Get the DB connection information $settings = parse_ini_file ("rss_server.ini"); / / look up the user's preferences... $link = mysql_connect ($settings ['db_host'], $settings [' user'], $settings ['password']) OR die (mysql_error ()); $max_stories = getUserMaxStories ($link, 25); / / go get my data $newsQuery = sprintf ("SELECT * FROM stories WHERE post_date ='% s'", mysql_real_escape_string (time (); $result = mysql_query ($newsQuery, $link) $feed = createRssHeader (); $I = 0; / / build the feed... While ($row = mysql_fetch_assoc ($result)) {if ($I < $max_stories) {$title = $row ['title']; $link = $row [' link']; $description = $row ['description']; $date = $row [' date']; $guid = $row ['guid']; $feed. = createRssItem ($title, $link, $description, $date, $guid) Else {break;} mysql_close ($link); $feed. = createRssFooter (); / / write the feed out to the server... Echo ($feed);}? >
Splitting a long method into a short method is also limited, and excessive splitting will be counterproductive. Therefore, do not abuse this good habit. Dividing the code into a large number of fragments is like not splitting the long code, which makes it difficult to read.
Add comments to the code
It sometimes seems as difficult to add good comments to your code as it is to write code. It is not easy to know what to comment on, because we often tend to comment on what the code is currently doing. The purpose of annotating the code is a good idea. In the less obvious header code block of the function, tell the reader the input and output of the method, as well as the original goal of the method.
It is common to comment on what the code is currently doing, but it is not necessary. If the code is complex and has to comment on what it is currently doing, this will imply that you should rewrite the code to make it easier to understand. Learn to use good names and shorter methods to improve the readability of your code without providing comments explaining its purpose.
Bad habits: too many or insufficient comments for functions
The comment in listing 5 simply tells the reader what the code is doing-it is iterating through a loop or adding a number. But it ignores why it does its current job. This makes the person who maintains the code wonder whether the code can be safely changed (without introducing new defects).
Listing 5. Bad habits: too many or insufficient comments for functions
severity = $sev; $this- > message = $msg;} public function getSeverity () {return $this- > severity;} public function setSeverity ($severity) {$this- > severity = $severity;} public function getMessage () {return $this- > message } public function setMessage ($msg) {$this- > message = $msg;}} function cntMsgs ($messages) {$n = 0; / * iterate through the messages... * / foreach ($messages as $m) {if ($m-> getSeverity () = = 'Error') {$nails; / / add one to the result;}} return $n;} $messages = array (new ResultMessage ("Error", "This is an error!"), new ResultMessage ("Warning", "This is a warning!"), new ResultMessage ("Error", "This is another error!")); $errs = cntMsgs ($messages) Echo ("There are". $errs. Errors in the result.n);? >
Good habits: annotated functions and classes
The comments in listing 6 tell the reader the purpose of the classes and methods. This comment explains why the code is doing its current work, which is useful for future maintenance of the code. You may need to modify the code in response to conditional changes, which can be easily modified if you can easily understand the purpose of the code.
Listing 6. Good habits: annotated functions and classes
Php/** * The ResultMessage class holds a message that can be returned * as a result of a process. The message has a severity and * message. * * @ author nagood * * / class ResultMessage {private $severity; private $message; / * * Constructor for the ResultMessage that allows you to assign * severity and message. * @ param $sev See {@ link getSeverity ()} * @ param $msg * @ return unknown_type * / public function _ _ construct ($sev, $msg) {$this- > severity = $sev; $this- > message = $msg;} / * * Returns the severity of the message. Should be one * "Information", "Warning", or "Error". * @ return string Message severity * / public function getSeverity () {return $this- > severity;} / * Sets the severity of the message * @ param $severity * @ return void * / public function setSeverity ($severity) {$this- > severity = $severity;} public function getMessage () {return $this- > message } public function setMessage ($msg) {$this- > message = $msg;}} / * Counts the messages with the given severity in the array * of messages. * * @ param $messages An array of ResultMessage * @ return int Count of messages with a severity of "Error" * / function countErrors ($messages) {$matchingCount = 0; foreach ($messages as $m) {if ($m-> getSeverity () = = "Error") {$matchingCount++;}} return $matchingCount } $messages = array (new ResultMessage ("Error", "This is an error!"), new ResultMessage ("Warning", "This is a warning!"), new ResultMessage ("Error", "This is another error!")); $errs = countErrors ($messages); echo ("There are". $errs. Errors in the result.n);? >
Handling error
According to popular experience, if you want to write a robust application, error handling should follow the 80 handle 20 rule: 80% of the code is used for exception handling and validation, and 20% of the code is used to do the actual work. This is often done when writing the basic logic (happy-path) code of a program. This means writing code that applies to the basic conditions, that is, all the data is available and all the conditions are as expected. Such code can be fragile in the life cycle of an application. At the other extreme, it even takes a lot of time to write code for conditions you've never encountered before.
This habit requires you to write enough error-handling code, rather than code to deal with all errors, so that the code cannot be completed.
Bad habits: there is no error handling code at all
The code in listing 7 demonstrates two bad habits. *, the input parameters are not checked, even though it is known that parameters in certain states will cause an exception to the method. Second, the code calls a method that may throw an exception, but does not handle the exception. When a problem occurs, the author of the code or the person who maintains the code can only guess the source of the problem.
Listing 7. Bad habit: do not deal with error conditions
Php// Get the actual name of the function convertDayOfWeekToName ($day) {$dayNames = array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); return $dayNames [$day];} echo ("The name of the 0 day is:". ConvertDayOfWeekToName (0). N); echo ("The name of the 10 day is:". ConvertDayOfWeekToName (10). "n"); echo ("The name of the 'orange' day is:" ConvertDayOfWeekToName ('orange'). "n");? >
Good habit: handling exceptions
Listing 8 shows how exceptions are thrown and handled in a meaningful manner. Additional error handling not only makes the code more robust, it also improves the readability of the code and makes it easier to understand. The way exceptions are handled is a good illustration of the original author's intention when writing the method.
Listing 8. Good habit: handling exceptions
< php/** * This is the exception thrown if the day of the week is invalid. * @ author nagood * / class InvalidDayOfWeekException extends Exception {} class InvalidDayFormatException extends Exception {} / * Gets the name of the day given the day in the week. Will * return an error if the value supplied is out of range. * * @ param $day * @ return unknown_type * / function convertDayOfWeekToName ($day) {if (! Is_numeric ($day) {throw new InvalidDayFormatException ('The value''. $day. '' Is an'. 'invalid format for a day of week.');} if (($day > 6) | | ($day < 0) {throw new InvalidDayOfWeekException (' The day number''. $day. '' Is an'. 'invalid day of the week. Expecting 0-6');} $dayNames = array ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); return $dayNames [$day];} echo ("The name of the 0 day is:". ConvertDayOfWeekToName (0). Try {echo ("The name of the 10 day is:". ConvertDayOfWeekToName (10). "n");} catch (InvalidDayOfWeekException $e) {echo ("Encountered error while trying to convert value:" $e-> getMessage (). "n");} try {echo ("The name of the 'orange' day is:". ConvertDayOfWeekToName ('orange'). "n");} catch (InvalidDayFormatException $e) {echo ("Encountered error while trying to convert value:" $e-> getMessage (). "n");}? >
Although checking parameters is a confirmation-it will be helpful to those who use the method if you require them to be in a certain state-you should check them and throw meaningful exceptions:
◆ handling exceptions should be as closely related as possible to the problems that arise.
◆ handles each exception specifically.
Never use copy and paste
You can copy and paste code from elsewhere into your own code editor, but this has both advantages and disadvantages. On the plus side, copying code from an example or template can avoid a lot of errors. The downside is that this tends to lead to a large number of similar programming methods.
Be careful not to copy and paste code from one part of the application to another. If you take this approach, stop this bad habit and consider rewriting the code as reusable. In general, placing the code in one place is easy to maintain later, because you only need to change the code in one place.
Bad habits: similar code snippets
Listing 9 shows several almost the same methods, but with different values. There are tools to help you find copied and pasted code (see Resources).
Listing 9. Bad habits: similar code snippets
getSeverity () = "Error") {$matchingCount++;}} return $matchingCount } / * Counts the number of messages found in the array of * ResultMessage with the getSeverity () value of "Warning" * * @ param $messages An array of ResultMessage * @ return unknown_type * / function countWarnings ($messages) {$matchingCount = 0; foreach ($messages as $m) {if ($m-> getSeverity () = "Warning") {$matchingCount++;}} return $matchingCount } / * Counts the number of messages found in the array of * ResultMessage with the getSeverity () value of "Information" * * @ param $messages An array of ResultMessage * @ return unknown_type * / function countInformation ($messages) {$matchingCount = 0; foreach ($messages as $m) {if ($m-> getSeverity () = "Information") {$matchingCount++;}} return $matchingCount } $messages = array (new ResultMessage ("Error", "This is an error!"), new ResultMessage ("Warning", "This is a warning!"), new ResultMessage ("Error", "This is another error!")); $errs = countErrors ($messages); echo ("There are". $errs. Errors in the result.n);? >
Good habit: reusable functions with parameters
Listing 10 shows the modified code, which puts the copied code into a method. Another method has also been changed, which now delegates the task to the new method. Building a common approach takes time to design, and doing so allows you to stop and think instead of instinctively using copy and paste. However, when changes are necessary, the time invested in the general approach will be rewarded.
Listing 10. Good habit: reusable functions with parameters
< php / * * Counts the messages with the given severity in the array * of messages. * * @ param $messages An array of ResultMessage * @ return int Count of messages matching $withSeverity * / function countMessages ($messages, $withSeverity) {$matchingCount = 0; foreach ($messages as $m) {if ($m-> getSeverity () = $withSeverity) {$matchingCount++;}} return $matchingCount } / * * Counts the number of messages found in the array of * ResultMessage with the getSeverity () value of "Error" * * @ param $messages An array of ResultMessage * @ return unknown_type * / function countErrors ($messages) {return countMessages ($messages, "Errors") } / * * Counts the number of messages found in the array of * ResultMessage with the getSeverity () value of "Warning" * * @ param $messages An array of ResultMessage * @ return unknown_type * / function countWarnings ($messages) {return countMessages ($messages, "Warning") } / * * Counts the number of messages found in the array of * ResultMessage with the getSeverity () value of "Warning" * * @ param $messages An array of ResultMessage * @ return unknown_type * / function countInformation ($messages) {return countMessages ($messages, "Information") } $messages = array (new ResultMessage ("Error", "This is an error!"), new ResultMessage ("Warning", "This is a warning!"), new ResultMessage ("Error", "This is another error!")); $errs = countErrors ($messages); echo ("There are". $errs. Errors in the result.n);? >
Concluding remarks
If you develop the good habits discussed in this article while writing PHP code, you will be able to build code that is easy to read, understand, and maintain. Maintainable code built in this way reduces the risk of debugging, repairing, and extending the code.
Using good names and shorter methods can improve the readability of the code. The purpose of annotating the code is to facilitate code understanding and expansion. Handling errors properly makes your code more robust. * stop using copy and paste, keep the code clean and improve reusability.
These are the five good habits of PHP programming shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 285
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.