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.
- /**
- * User request to reset password receiver
- */
- function Requestresetpassword () {
- //Check whether the user exists
- if (!checkuserexists ( $_get[' userid ')) {
- exit (' Sorry, the user does not exist, please confirm the user account. ‘);
- }
- ResetPassword ( $_get[' userid ');
- //Finally send a message to the user
- SendEmail ( $_get[' userid '), ' Reset password succeeded ', ' new password is xxxx ');
- exit (' The new password has been sent to your mailbox. ‘);
- }
- /**
- * Help users reset their passwords
- */
- function ResetPassword ( $userid) {
- //Check whether the user exists
- if (!checkuserexists ( $userid)) {
- return false;
- }
- //To reset the user's password
- //slightly ...
- return true;
- }
- /**
- * Send an email to the user
- */
- function SendEmail ( $userid, $title, $content) {
- //Check whether the user exists
- if (!checkuserexists ( $userid)) {
- return false;
- }
- //Send mail action
- //slightly ...
- return true;
- }
- /**
- * Check if a user exists
- */
- function checkuserexists ( $userid) {
- $user = GetUserInfo ( $userid);
- return! emptyempty ( $user);
- }
- /**
- * Get data from a user
- */
- function GetUserInfo ( $userid) {
- //Suppose I have a query function that is used to query the database and return the data
- $user = Query ( "SELECT * from ' user ' WHERE ' uid ' =".) intval ( $userid));
- return Is_array ( $user)? $user: Array ();
- }
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:
- /**
- * Check if a user exists
- */
- function checkuserexists ( $userid) {
- //Add a cache to record the results of checking users
- static $cache = Array ();
- //Check whether the current user has checked once
- if (isset ( $cache [ $userid])) {
- return $cache [ $userid];
- }
- $user = GetUserInfo ( $userid);
- //Record the results in the cache
- $cache [ $userid] =! Emptyempty ( $user);
- return $cache [ $userid];
- }
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:
- Good name
- Class Erasedtypeequivalence {
- }
- Bad Name
- Class Erdtypeeqe {
- }
- Good name
- function checkuserexists () {
- }
- Bad Name
- function Ckuserext () {
- }
- Good name
- $result;
- Bad Name
- $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?
- function Requestresetpassword () {
- if (!checkuserexists ( $_get[' userid ')) {
- exit (' Sorry, the user does not exist, please confirm the user account. ‘);
- }
- ResetPassword ( $_get[' userid ');
- SendEmail ( $_get[' userid '), ' Reset password succeeded ', ' new password is xxxx ');
- exit (' The new password has been sent to your mailbox. ‘);
- }
- function ResetPassword ( $userid) {
- if (!checkuserexists ( $userid)) {
- return false;
- }
- //To reset the user's password
- //slightly ...
- return true;
- }
- function SendEmail ( $userid, $title, $content) {
- if (!checkuserexists ( $userid)) {
- return false;
- }
- //Send mail action
- //slightly ...
- return true;
- }
- function checkuserexists ( $userid) {
- static $cache = Array ();
- if (isset ( $cache [ $userid])) {
- return $cache [ $userid];
- }
- $user = GetUserInfo ( $userid);
- $cache [ $userid] =! Emptyempty ( $user);
- return $cache [ $userid];
- }
- function GetUserInfo ( $userid) {
- $user = Query ( "SELECT * from ' user ' WHERE ' uid ' =".) intval ( $userid));
- return Is_array ( $user)? $user: Array ();
- }
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.
- Example One
- function func () {
- }
- Example Two
- function func ()
- {
- }
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)