Programming Idea: I'm programming this now (turn)

Source: Internet
Author: User

The world of code may be out of the sky, but our minds can't be so chaotic, otherwise everything will be wasted. So when I'm writing a program, I often think about what I'm going to do, what I'm doing. A better approach is to implement the detailed requirements into the documentation and check the documentation at all times.

AD:

What am I doing here?

Once, I tried to get some demand. After a glance, the head immediately indulged in the world of code with high morale, banging on the keyboard until the final test was complete. I recovered from my thoughts, at first glance I wrote the function, and the demand is 108,000 miles, what I TM are doing?

Besides, I've seen something very funny like that. There was a programmer, the manager raised the demand, and then he was there to toss the day. Not only did the results not come out, but the actual demand was not raised. He did not know what the manager said or what he was doing, after asking.

The world of code may be out of the sky, but our minds can't be so chaotic, otherwise everything will be wasted. So when I'm writing a program, I often think about what I'm going to do, what I'm doing. A better approach is to implement the detailed requirements into the documentation and check the documentation at all times.

The big picture

The 2-8 rule tells us that there are only a few functions at the core of a project, and most of the others are auxiliary or enhanced for core functions. But when the task was distributed, I always had some modules I wanted to develop, but they didn't belong to that 20%. I used to spend a lot of time and energy on these interesting modules.

As a result, the project is nearing the end of the line, the main function has not been developed, and some other obscure functions have done very well, but the project has to be postponed. If the reverse, as long as the overall function is not expected to be too much deviation, can be on the first line. The important point is: even if the function is missing, but the project can go online, the boss will not be too much, his work can also be a peace of mind. If you do not know those functional modules are the most important, first ask the manager.

People always like to do something they are interested in or challenging. But in this regard, for the sake of the project and the team, we should try to suppress this temptation.

Performance is never a priority issue

I never think about performance from the start. If the project cost is very low, even at the end of the project, if you do not feel the obvious performance problems, will not go to the tube. To know that it is not the age of DOS, CPU computing power is very high, but the cost is very low. It is important that if you make changes to your code only for improved performance, you can easily compromise the reusability and maintainability of your code. It is easy to improve the performance of the code by improving its reusability and maintainability.

Here is a code example of PHP, which is to help the user reset the password (code in order to simply explain the problem, please do not care about some irrelevant details)

Requestresetpassword is a request to receive a user's password reset and a corresponding check is made. For better reusability, I assign the reset password operation separately to a new ResetPassword function, and then call SendEmail to send a notification message to the user after the password is changed.

  1. /**
  2. * User request to reset password receiver
  3. */
  4. function Requestresetpassword () {
  5. //Check whether the user exists
  6. if (!checkuserexists ( $_get[' userid ')) {
  7. exit (' Sorry, the user does not exist, please confirm the user account.  ‘);
  8. }
  9. ResetPassword ( $_get[' userid ');
  10. //Finally send a message to the user
  11. SendEmail ( $_get[' userid '), ' Reset password succeeded ', ' new password is xxxx ');
  12. exit (' The new password has been sent to your mailbox.  ‘);
  13. }
  14. /**
  15. * Help users reset their passwords
  16. */
  17. function ResetPassword ( $userid) {
  18. //Check whether the user exists
  19. if (!checkuserexists ( $userid)) {
  20. return false;
  21. }
  22. //To reset the user's password
  23. //slightly ...
  24. return true;
  25. }
  26. /**
  27. * Send an email to the user
  28. */
  29. function SendEmail ( $userid, $title, $content) {
  30. //Check whether the user exists
  31. if (!checkuserexists ( $userid)) {
  32. return false;
  33. }
  34. //Send mail action
  35. //slightly ...
  36. return true;
  37. }
  38. /**
  39. * Check if a user exists
  40. */
  41. function checkuserexists ( $userid) {
  42. $user = GetUserInfo ( $userid);
  43. return!  emptyempty ( $user);
  44. }
  45. /**
  46. * Get data from a user
  47. */
  48. function GetUserInfo ( $userid) {
  49. //Suppose I have a query function that is used to query the database and return the data
  50. $user = Query ( "SELECT * from ' user ' WHERE ' uid ' =".)  intval ( $userid));
  51. return Is_array ( $user)?  $user: Array ();
  52. }

Now the problem is that all three of these functions use the checkuserexists function to check that the user does not exist and that the database is queried three times, which brings some extra overhead.

If you want to remove any one of the checkuserexistsbetween the three, it seems possible. However, if there are certain features to call ResetPassword or sendEmailafter the user does not exist, the system may get an error.

Another solution is to write the logic of the ResetPassword into the Requestresetpassword , and then a little more, and write the sendEmail logic in it. This reduces the function call, and the database query becomes one time, and the performance is improved. But the ability to reset passwords and send messages will not be reused, and it violates the principle of single responsibility and increases the complexity of the code.

However, because the function separation and reusability are good, if the actual performance is affected, may consider the cache method to reduce the database query, I changed their common checkuserexists function:

  1. /**
  2. * Check if a user exists
  3. */
  4. function checkuserexists ( $userid) {
  5. //Add a cache to record the results of checking users
  6. static $cache = Array ();
  7. //Check whether the current user has checked once
  8. if (isset ( $cache [ $userid])) {
  9. return $cache [ $userid];
  10. }
  11. $user = GetUserInfo ( $userid);
  12. //Record the results in the cache
  13. $cache [ $userid] =!  Emptyempty ( $user);
  14. return $cache [ $userid];
  15. }

You can also change the getuserinfo function in the same way.

As you can see here, when the reusability of code increases, it is very easy to improve performance, and the bottleneck of performance is easy to be discovered and modified.

Although the performance impact of this example is not large enough, there are some more impact, such as traversal, I may be used for reuse to wrap the traversal into a function, and use it more than once. These costs have had too much impact, or minimal, on my project at all. So I prefer to spend more time on how to improve the reusability and maintainability of the code, rather than the waste of this performance. If the actual performance is not up to the requirement, you can also weigh the additional hardware configuration.

Name a little longer.

function names and variable names, etc. in addition to the machine to see, but also to show people, sometimes a simple and direct good name is very difficult to think, it may be better to use a longer name. Better readability:

  1. Good name
  2. Class Erasedtypeequivalence {
  3. }
  4. Bad Name
  5. Class Erdtypeeqe {
  6. }
  7. Good name
  8. function checkuserexists () {
  9. }
  10. Bad Name
  11. function Ckuserext () {
  12. }
  13. Good name
  14. $result;
  15. Bad Name
  16. $ret;

I have seen some code, because the simple write too much, the whole code is a lot of 4 letters or below, the readability is very poor, of course, do not rule out to be lazy.

But if you want to have more time to be lazy, should not play smart on this, otherwise I should now be thinking about the days before the code is what to write.

What the? Will the short name make the code run faster? That proves to me, if really fast, how much faster?

Self-explanatory code is important, but annotations are equally important

The code itself shows that the problem is really great, but not that it doesn't matter, and sometimes I prefer to read the comments first, because it's always faster than I see the code to know what the program does.

If I remove the comment from the example described earlier in this article, which will give you a faster idea of the code? Or, what would you rather see?

  1. function Requestresetpassword () {
  2. if (!checkuserexists ( $_get[' userid ')) {
  3. exit (' Sorry, the user does not exist, please confirm the user account.  ‘);
  4. }
  5. ResetPassword ( $_get[' userid ');
  6. SendEmail ( $_get[' userid '), ' Reset password succeeded ', ' new password is xxxx ');
  7. exit (' The new password has been sent to your mailbox.  ‘);
  8. }
  9. function ResetPassword ( $userid) {
  10. if (!checkuserexists ( $userid)) {
  11. return false;
  12. }
  13. //To reset the user's password
  14. //slightly ...
  15. return true;
  16. }
  17. function SendEmail ( $userid, $title, $content) {
  18. if (!checkuserexists ( $userid)) {
  19. return false;
  20. }
  21. //Send mail action
  22. //slightly ...
  23. return true;
  24. }
  25. function checkuserexists ( $userid) {
  26. static $cache = Array ();
  27. if (isset ( $cache [ $userid])) {
  28. return $cache [ $userid];
  29. }
  30. $user = GetUserInfo ( $userid);
  31. $cache [ $userid] =!  Emptyempty ( $user);
  32. return $cache [ $userid];
  33. }
  34. function GetUserInfo ( $userid) {
  35. $user = Query ( "SELECT * from ' user ' WHERE ' uid ' =".)  intval ( $userid));
  36. return Is_array ( $user)?  $user: Array ();
  37. }

So, even if the code itself is clear, but with comments, readability can also improve a lot!

Appropriate abstraction

Programming is to solve the problems in the real, when thinking about how to encode, the problem is abstracted to a certain height to think, more easily grasp the problem. But more often, I find that from the code abstraction to the real example is a certain difficulty, and I also believe that the programmer is also an abstract master, they can easily reflect the problem into the real life.

However, if you keep an eye on and think about the details of your life, you will be able to improve your abstraction.

As an example of a screwdriver, what would you do if you were asked to build a screwdriver? I have three different screwdrivers here:

Obviously the first type of screwdriver is the simplest and more modest.

The second screwdriver can be rotated in the middle to make the shank and the head 90 degrees, making it easier to screw screws.

The third type of screwdriver can be changed, if there are other types of screws, then just create a suitable for this kind of screw head can be.

That reflects the problem in programming, if the project is to add a tool class library.

The first way, you can directly write the required functions of the class library.

The second method not only writes out the class library, but also makes special improvements to some of the project's circumstances, making it much better to use in this project.

The third method, according to the characteristics of the class library, the public part of the logic of the interface, the special partial separation out of a separate implementation, if later to increase the same type of class library, the implementation of the special part of the logic, and then access the interface.

But when it comes to abstraction, avoid unreasonable abstractions, and sometimes design transitions, and now you only need a screwdriver, but you've made more types of screwdrivers (and the Swiss Army knife). ):

Consistency

In team development, there may be different programming styles for everyone, and with curly braces, some people like to be on the same line as the code, while others prefer to be alone.

    1. Example One
    2. function func () {
    3. }
    4. Example Two
    5. function func ()
    6. {
    7. }

Naming styles are also different, for example declaring variables to receive data returned by a function, some like to use result, and some like data.

They may be good, but in team development, the same style can be used to minimize the cost of cross-development.

Will wrong

It should be accepted and understood in the face of some irrelevant disagreements or mistakes in the project. To take the above question, if someone in your team already has a large number of data variables named, but you think the result is more in line with the current state of the description. In this case, I prefer the data name, because if you use result again, it will break the consistency of the project, there is no benefit to development.

This is only a very small aspect, if the project specification is not well implemented, there will be a lot of consistency in the actual work, it must rely on the determination and responsibility of each team to do it well. Usually, before I join a project under development and write a function, I look at the similar code before the project and try to imitate their writing. However, if there are obvious errors, it should be pointed out and amended in time.

As long as we insist on consistency, many methods will become the standard of the team and even the industry, even if they are not the best, but what is the relationship?

Proper rest

If you are not thinking or confused when you are programming, it is good to take a 10-minute break from the outside, or to look at the scenery to make your head clear. This is a good trick, a pro-test.

At least run the code completely once

Sometimes the logic of a function is too simple to assume that it is impossible to make a mistake, but in fact it is usually the code that is most prone to errors, common spelling mistakes, incorrect parameters, and some unexpected problems. So whatever the case, I'll run the code all over again.

Of course, a better approach is to use some systematic testing methods, such as unit tests.

Programming is not art

From the beginning, the emergence and development of programming language is to solve real-life problems, including its own problems.

The appearance of object-oriented and design patterns is used to solve the problems of readability and maintainability of the programming language itself, rather than to bring the programming language up to the artistic level. Although there is the word ' elegance ' in programming, I think it is only used to describe code that is easier for people to read and maintain.

I reject all the code that seems ' elegant ' and does not bring a little benefit to the programming effort. If you like to play with language, you should be a writer.

Be willing to ordinary

Programmers are really arrogant, and I've been in contact with myself, including myself. I used to have a lot of disdain for some simple code, and always want to write some sharp code in the project, so that people look very NB, but the result is always too far from the imagination, the code is always poor, logic is not clear. In the final analysis, I write the code with this idea, ignoring the root of the programming: solving the problem. Now I get rid of this bad habit, to solve the problem for the purpose of programming, to simple-dominated. The unexpected is that people sometimes say to me that the code here is very good.

Practical work, there will be unexpected gains.

Admit mistakes

Don't doubt that when someone else is unable to run with their own program or code, the first thing to consider is whether your own logic is in trouble. The other person will feel that I am modest, and the actual majority of the situation is indeed their own problems.

Have a principle, have the determination

To do everything is to stick to the principle and have the determination to be the best. There are many reasons we understand, but often do not, no one can help themselves, the future is also their own fight.

So, if you know what is good, try to do it, what is not good, try to avoid.

Even in the face of the company managers and leaders, but also adhere to their own practices, some unreasonable needs should be pointed out or rejected. I am still young, a big deal to change a company, rather than to be a bully of the yards farmers.

What am I doing here?

The article is finished, now to recall, I am sharing some of my current programming habits, and finally did not deviate from the beginning of the topic. The idea of this article is from the actual work and some books, want to know more words, recommend reading "Clean Code of the Road" "Code Encyclopedia" "Refactoring" these books.

If you have some programming methods that you think are good, you might as well share them with you.

Programming Idea: I'm programming this now (turn)

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.