30 principles of defensive programming thinking that programmers must have

After analyzing several online problems, you will find that many problems are not very rare problems, but are caused by the accumulation of obvious small mistakes. Why do you make small mistakes? Maybe it's because of luck, maybe because we only see partial benefits. Judging from a certain example, there is indeed a fluke of "if you make a mistake, you will become a superior person", but statistics of a large number of cases show that most of the cases will not have positive results.

This article compiles the principles I have summarized in the stages of requirements review, coding, and project launch. Although these principles cannot directly solve the problem, they can optimize every step of the behavior as much as possible, and try to avoid errors from the perspective of defensive programming thinking and behavioral habits. occur.

principles of communication

Different scenarios use different communication tools

Typing via IM (Instant Messenger) is a common communication method with low cost, suitable for communication of simple issues and notification of various information within the team. But if a complicated question is still unclear and no progress is made after typing for 3 minutes, you should immediately switch to a more efficient communication method, such as voice or face-to-face.

Compared with text communication, voice communication has tone, which can avoid the problem of blunt tone of pure text, and has more information output per unit time, which is more efficient. Sometimes I see two people talking one by one in the group and discussing for 5 minutes, only to find out that what they said is not the same thing. If you switch to voice in time, you may find the problem in 1 minute.

Compared with speech, face-to-face communication has added expressions, which can better express strong appeals. Especially when encountering very urgent problems, meeting directly is the best way. Sometimes there is an online problem, and I am still waiting for others to reply through IM, which may affect the best stop loss time.

Avoid confirmation bias, opposing views may lead to more revelations

Confirmation bias refers to only listening to "good" news-that is, news that can confirm one's own ideas, and killing "bad" news-refusing to accept news and ideas that are different from one's own ideas. This phenomenon can lead to an inability to accept a long-term beneficial objection.

This situation will be more obvious when looking at the information flow in the era of big data. After precise algorithms, when you have a point of view and like a certain type of point of view. The precise recommendation algorithm is only for continuously recommending information that you agree with. There will be no negative information to correct wrong views. Strengthening wrong views in this way will put you in an information cocoon where you can't call yourself.

This is because the structure of the brain is very complex, consisting of a rational self and an emotional self. Regarding other people's objections, the emotional self will acquiesce in taking other people's objections as attacks.

So we have to train our emotional self to think carefully about other people's opinions before taking action. The opposing point of view may reveal the potential risks in one's own ideas, or even enlightenment of a better plan. By training the ability of active dialectical thinking, distinguish between "views that sound comfortable" and "views that are beneficial to you in the long run".

Demonstration with examples can only be used as a reference for decision-making

Whether you are thinking about a problem by yourself or discussing a problem, the following two viewpoints often appear.

  • In the last project, I used technical solution A, and the effect was very good, so this project should also use technical solution A.

  • I have a classmate who encountered such a problem and he solved it this way, so we can do the same.

The phenomenon of taking an accidental success as an inevitable conclusion. It may come up both in discussions and in one's own experience. These experiences can be used as a reference case for decision-making, but they cannot be directly regarded as inevitable conclusions. Scientific methods should make large-scale statistics according to different scenarios and backgrounds, so that better decisions can be made according to different scenarios.

Choose the best ideas, adjust the weights before making decisions

Whether it is a discussion of a technical solution or a communication on a controversial issue, everyone will have different opinions from their own perspectives. Everyone has their own points of more concern, and their positions are different, and their concerns are different. If you need to make decisions by yourself, then in the process of discussion, you must understand the reasons behind each idea, so that you can understand its underlying logic and judge its weight from your own perspective. Comprehensively consider ideas from different perspectives, so that you can consider and make decisions more comprehensively from your own perspective.

When Kai-fu Lee chose the topic of his graduation thesis, he involved the choice of two types of topics: risk and stability.

  • If you choose deep learning, your graduation may be postponed, and the risk is high, but if you succeed, you will become famous in one fell swoop.

  • If you choose an ordinary subject, you can graduate on time without risk, but you will not achieve great achievements.

For different people, the risks they bear are different, so their choices will be different, and of course, their long-term benefits will also be different.

When typing, send a separate message for important content

For large paragraphs of text content, the other party may not necessarily read every sentence carefully. Important questions should be posted separately and not combined with other content.

Example 1: When troubleshooting a problem, two questions were asked in one sentence, and the other party answered "yes". Based on the other party's conclusions, I continued to troubleshoot the problem. After a day of investigation, I felt that the situation of problem B should not be B1. I checked with the other party again, but the other party said that he only saw the previous sentence I said, but did not see the latter sentence "The situation of problem B is B1, right?".

Example 2: Once the project was launched, I sent a sentence to express my gratitude to the partner, and the other party replied to me: "What problem do I need to cooperate with in troubleshooting?"

Meeting minutes, which can highlight the value when working across teams

The meeting host should record the conclusions and to-do items of the meeting in real time. Otherwise, after a few days or weeks, everyone will have different conclusions and lead to conflicts, and even forget important to-do items.

For the internal team, this kind of problem will not be a big problem. After all, everyone has cooperated for a long time, and even a little mistake will be tolerated, but we cannot lose this habit because we are often tolerated. Because in a larger community, when the company cooperates with horizontal teams, or even cooperates with external companies, the negative impact of this problem will be multiplied.

For some third-party suppliers of customized functions, they will connect with many teams. When they communicate with the outside world, it is not research and development, but students in other positions, such as sales or business. They will inevitably make wrong answers due to misunderstandings during the docking. If an unreasonable technical solution is designed based on a wrong conclusion, the problem will not be discovered until the early stage of the project launch. Without meeting minutes, it is difficult to prove that it is true. The other party said it wrong, or I misunderstood it.

Principles of Requirements Review and Scheduling Stage

Everyone is a product manager, demand determines the direction

Software development is to meet the needs of users, solve practical problems, and create value, not just for the assigned tasks. R&D requires not only writing code according to the needs of product managers, but also thinking about and criticizing its rationality. Only by carefully analyzing the rationality of the product from the perspective of a user can we write more valuable code, instead of just treating writing code as an exchange of manual labor.

Technology is a means, not an end

Requirements analysis and system design are two progressive steps.

In the requirements analysis stage, detailed technical details should not be considered, otherwise there will be "because the technology is too difficult, so this requirement cannot be fulfilled" or "this workload is too large, please change the requirements, so that the workload will be reduced a lot" The phenomenon that leads to the miscarriage of an excellent idea. At the very beginning, a more valuable product is realized from the perspective of technology rather than from the perspective of users' real needs. The value of a product should be determined based on the needs of users, not the difficulty of technology. Of course, it is not that the cost of technology implementation is not considered, but there should be a sequence, and the cost of technology implementation should be confirmed after the requirements are determined. After all, even if the technology cost is high, its ROI may be higher.

Although there are some requirements, with some technical solutions, the cost is very low. It takes a few hours to complete a requirement, but if it is a meaningless requirement and a meaningless technical solution, what is the use of doing more?

Products with simplified steps have greater value

For products that require user interaction, the lower the user operation cost, the lower the time cost, and the higher the value. This requires that when considering the product, on the premise of ensuring that the functions remain unchanged, as many redundant functions as possible should be deleted instead of adding functions, although adding functions is easier.

Collaborate across teams, and communicate with the outside after all internal schedules are aligned

From individuals, to teams, to the entire company, and then to external companies, the community gradually increases, and the cost of communication will gradually increase. For some issues that require a unified conclusion, such as project scheduling, it should be gradually determined according to the size of the community from small to large. Avoid confirming a project launch date with the external team, only to find that the internal time cannot match, and then adjust with the external team later. On the one hand, the cost of communication will be very high, on the other hand, it also exposes the confusion of internal processes.

Reverse scheduling requirements, pay attention to holidays, and ensure joint debugging time

Sometimes it is inevitable to encounter very urgent needs and need to reverse the schedule. If you must compress the time, then compress the development time and ensure that the joint debugging time is sufficient. Because joint debugging can expose problems faster. Only by exposing problems in advance can we coordinate resources and solve problems as soon as possible.

Try not to start the joint debugging one day before a large-scale holiday, especially for a large project involving multiple teams, because one person is on vacation and the joint debugging cannot be started, and eventually the entire process cannot start the joint debugging in time.

Do not evaluate the workload of the partner

When it comes to cooperation with brother teams or even external companies, you may encounter a situation that requires the other party to add or modify a function. From your own point of view, this function only takes a few minutes to complete, but as long as you don't have permission to change the code, don't evaluate the workload of the other party from your own point of view.

On the one hand, each person has a different degree of familiarity with each function, and the other party may have just taken over the code and is not very familiar with it. On the other hand, each team has its own process, and the marginal cost of completing the modification of the entire function is not low. Because it is not only necessary to develop and modify the code to meet the current functions, but also consider the scalability and stability, and even the collaboration of teams such as testing.

Principles of the development phase

Perfect documentation is a manifestation of long-term strategic vision

Treat the entire team that may be involved in the project as a community, not just yourself. Compared with the local perspective of writing a document once, you can look at the long-term benefits from a more global perspective. For the requirements of multi-team cooperation, if it is not recorded, it may seem like an unimportant parameter, which may involve the cost of communication and collaboration of a large number of teams. Although when maintaining other people's projects, you can look at the code or comments to understand the entire project. However, for some complex projects and more complex logic, it is difficult to see the overall structure from the code. At this time, the importance of documentation is revealed.

Documentation does have a cost to maintain, but it is a short-term cost. In the long run, with documentation, you can avoid more communication costs in the future, and avoid spending more time looking at an unfamiliar logic. Compared with overthrowing and starting over after coding is completed, the cost of document modification is not high.

Facing the two ends of the short-term and long-term balance, which end are you willing to put the weight on? Life is a marathon, although there will be short-term ease if you don't write documents. But from a long-term perspective, it is actually more important to have a long-term vision, a broader perspective, and a long-term strategic vision.

In addition, some people think that documentation should be written, but only for complex projects, and there is no need to write simple projects. In fact, simple projects are a good opportunity to train habits. If you have never been in the habit of writing documents, then when you own a large-scale project, you will find that you are not used to writing documents. When time is tight, functions are complex, and projects involving a lot of teams are involved, actions are easily deformed under heavy pressure. If you want to ensure that your movements are coherent and smooth, you must develop good habits in normal times.

While maintaining the document, also maintain the document index

If it is a document of a single project, its structure is relatively simple, and even if it iterates multiple versions, its overall structure is relatively clear. But if it is a team that everyone records together, for the addition of a new topic page, different people will add it to different levels, and it will be very difficult to find it next time. At this time, the importance of the index is obvious, that is, the addition of a document is not only the addition of a single document, but also the maintenance of the corresponding index.

This actually involves a problem in modern electronic document storage, with many types, flexible classification, and endless changes in levels. As the size of the team grows and the number of projects increases, the disorder will continue to lead to an increase in entropy. To be neater, indexes are essential.

Coding time should be less than 30%

A project starts from requirements review, technical solution research, document writing, code writing, testing, and launch. The proportion of pure coding time is not large. Especially when the design is perfect and the code is written in one go. If the coding time takes up a large proportion, it is most likely because I wrote half of it during the coding process and suddenly didn’t know how to write it later, or after I finished writing, I found out that the design had serious flaws and I needed to overthrow it and start over.

Code needs to be understood by others, not just run normally

During the school period, a curriculum design project, as long as it can run normally. It doesn't matter whether the teacher can understand what our variable naming means. Because of this project, no one will pay attention to it in the future. But in enterprise projects, a project not only needs to be maintained by itself, but also involves other students in the team to maintain it. Therefore, the requirements for the code are not only to be able to run, but also to be understood by others.

Write comments first, then code

Comments are not made up, but should be written when coding.

Code and comments are an inseparable unity, similar to the idea of ​​unity of knowledge and action, knowledge and action are closely combined, and the two are inseparable. Typing a few words and writing some notes in a few seconds will save more time for later viewing. Some people may say that as long as I can understand it, if I don’t understand it in the future, others will not understand it, and it has nothing to do with me. Even if you only look at it from your own point of view, this is not necessarily true. If you don’t believe me, you can look at the code you wrote 2 months ago. Moreover, from the perspective of the larger community interests, writing annotations is not for oneself, but for the interests of the whole group. If you are not used to writing comments while writing code at the beginning, you can write comments before writing code.

Diplomacy is no small matter, the external interface, the change of variables, should be synchronized as soon as possible

The external interface protocol should be cautious, and should not be modified after confirmation. But if it is necessary to revise because early consideration was not comprehensive, revise it as soon as possible. Although the cost of global search and replacement is very low, if it involves modification by partners, especially in the later stage of testing, the communication cost may be an order of magnitude higher. Know the upstream and downstream, the sooner the change, the lower the relative cost for everyone.

Modules and functions follow the principle of single purpose

Each function only does one thing, and the function of each module is as single as possible. Each module exposes the corresponding interface to the outside, so as to achieve "high cohesion and low coupling". It seems very simple to say, but if you write highly coupled code in the first version of the requirement, it will lead to uncontrollable follow-up maintenance, and there will be thousands of lines in a class. If you want to change it later, the cost will rise exponentially. For each function, try not to exceed 30 lines. For each class, try not to exceed 900 lines.

Naming should be the same as the outside and inside, see the name and know the meaning

Variables are the smallest unit in the code, and the quality of naming has a lot to do with the readability. For example, if the name is keyString, the meaning should be the string of the key value. If the value is used when using it, it will cause great obstacles for others to read.

Encoding: don't use special tricks

Very complex gimmick code whose value is not worth mentioning in the face of readability. If it can be open source, it can be regarded as a show of style, otherwise it is self-promotion.

Commit message is unremarkable, but contains big information

Commit message can be used as an index, which is not only convenient for reviewing the iterative process, but also convenient for rollback. Each commit message should be similar to the single purpose of modules and functions, and try to modify only one function. And the commit message should preferably have a fixed format, such as [branch name][modified content]. If you want more details, you can add [code type] to distinguish whether it is a function or a bug fix. You can even add [bugId] to link to the corresponding bug space. This habit realizes its value when it is integrated and rolled back.

Code review is the feedback after input and output, and it is one of the fastest ways to improve

Code review: When someone finds my mistake, I should be grateful instead of trying to explain it. Just like when exercising, first read the theory in the book, then practice, and finally seek feedback from the coach. Sometimes we think that the actions we are doing are correct, but we can correct many mistakes caused by careless details by looking for feedback from the coach after the output. The same is true for code reviews. Sometimes you think your writing is perfect, but it may actually be full of loopholes.

If else balance, failed data also need

For some logic processing, output the success result for transparent transmission. While only the success case needs to be handled, the failure case should also be handled. Although the failed data is temporarily useless, you can count the failure rate and analyze the problem.

Principles of the testing phase

For product functions involving user operations, cross-testing makes it easier to find problems

Each user has different operating habits. For product functions involving user operations, if the same QA tester is used all the time, it may not be easy to find some hidden bugs because of its fixed operating habits. At this time, as many "user" operations as possible, and experience from different operating habits, it is easier to find problems. If the scope can be further expanded, and students in different positions use, experience, and complain together, then the experience problems of real users can be discovered earlier.

Difficult problems that cannot be solved, try research ideas

Sometimes you come across a problem that is so difficult that you can't solve it for a day. There are mainly two situations:

  • The idea is wrong.

  • There is too much unknown knowledge.

If the idea is wrong, you may wish to retreat at this time, think about why you want to develop this function, or even return to the demand level, whether there are other simpler solutions. From a higher perspective, you can avoid getting caught in local details and being unable to dial yourself.

If there is too much unknown knowledge, it is not necessary to solve this problem directly, but to learn all the relevant knowledge with the idea of ​​research, and it is possible that this difficulty will be solved easily. If time is limited, you can ask others, and make a record, and then summarize it yourself later, and seize the growth opportunities brought about by solving the problem.

Principles after launch

By coincidence, by odd victory

There is almost no surprise victory based on luck. Only on the premise of having enough positive strength and some extra strength can the final victory be achieved, and the same is true when doing projects.

If you want to complete a project faster and more efficiently, you cannot do without daily accumulation. The launch of the project is not the end, but the beginning of growth. A project can provide a lot of experience and materials, which can be used as a kind of feedback for your own input and output, so as to find the shortcomings and avoid making the same mistakes next time.

Grow under the halo of the company, not alone

What do you do in your spare time, find a side job? In the short term, it is true that there will be some extra income, but in the long run, even if the income is increased by 30%, there will be no essential changes. It is nothing more than being able to replace some higher-end electronic products, clothing, and daily necessities. Personal strength is too weak, so it is better to achieve personal growth on the premise of completing projects more efficiently under the aura of the company.

On the one hand, it is because the company's platform has more resources, and on the other hand, based on the growth of the company's projects, the marginal delivery cost is lower. Based on existing projects, dig deep into the underlying principles related to them, so as to accumulate and grow faster. When doing simple projects, the role of the underlying principles is not obvious, but for very complex projects, when the support of the underlying principles is needed, the accumulated technology will exert obvious effects.

In the face of online problems, anxiety is meaningless, the important thing is to find immediate solutions

Worrying about the past or worrying about the future doesn't help when it comes to online issues. Focus on the present moment, and calmly and actively seek solutions. Failure can be a motivator for personal growth or self-destruction, depending on how we respond to it. It is not anyone or anything that can defeat you, but yourself. When something goes wrong online, there are two things to do:

  • How to solve the current situation.

  • Review the reasons and avoid making the same mistakes next time.

In view of the current situation of "an accident has occurred online", it is necessary to find a solution immediately, which is the highest priority when encountering an online accident. Stop loss is very important, especially when the loss is constantly expanding. At this time, every operation is very important. If the problem is very complicated, remember to call more people. Pull the boss and experienced classmates into the group. After all, in a hurry, I may not think comprehensively. If you don't see the news, just call directly.

When analyzing the reasons, if it is a complex project involving a lot of teamwork, there are actually a lot of reasons, and analysis from different angles will lead to different results. In the review meeting, try to express the objective actual situation as much as possible, instead of being afraid, especially for introverted students. Avoid not speaking at the meeting and regretting it after the meeting, and don't be stingy to express when it is time to express.

From my point of view, it's not that "as long as this online problem has nothing to do with me", I don't need to pay attention. This kind of problem is a very good negative teaching material. Even if it has nothing to do with yourself, it can also be used as material to avoid making mistakes next time.

For example, some of the principles in this article have nothing to do with me, but when I saw these problems, I made a summary to avoid making the same mistakes myself. The worst case is that you make a serious mistake and cause a large loss. In the face of painful experiences, whether to escape or actively respond depends on one's own attitude. Don't be overwhelmed by pain, but use pain as fodder for reflection. Pain + reflection = growth.

Man proposes, God disposes

Separate the effort and the result, and the relationship between them is similar to the pursuit of goals and accessories. Sometimes we have paid a lot, but the result is very sad. At this time, we will use Adler's subject separation. The contribution is something we can control, but the result is not, so we must separate the effort from the result.

From another perspective, it can also be considered from the perspective of goals and accessories. If we are after results, it will be very sad indeed if we fail. But if the result is an accessory and the process is the goal, then the result is not important anymore.

Polite interaction

Everyone is welcome to chat with us in the comment area " What principles do you sum up in your work to optimize your daily behavior? " The 3 friends with the highest number of likes will receive Didi customized computer bags, August 29 Draw at 9pm.

c8df45c37d7c5d032abb9ed7a2a6b1ff.png

Guess you like

Origin blog.csdn.net/DiDi_Tech/article/details/132439888