Recently, I was very touched by the "programming craftsmanship" written by Pete goodliffe. Reading and thinking, and discovering strong resonance with the author, is a wonderful feeling. Therefore, I want to write down some areas that resonate with the author and are worth learning, so as to deepen my understanding of these proven programming skills.
Defensive Programming: As the name suggests, defensive programming is a meticulous and cautious programming method. In order to develop reliable software products, every detail of the system should be carefully designed so that it can do its best.
"Protect" ourselves, and we use clearCodeA lot of assumptions are added. When the assumption is executed in the real customer environment, it will not crash, giving some customers an inexplicable error or exception. Defensive Programming is a defense method, not a remedy.
Figure 1 disruptive Programming
The following are common Defensive Programming Skills:
1.
Good coding style and reasonable design:
A good coding style is refreshing. The clearer the code, the clearer the definition of the author's ideas. The high cohesion in the module components and the low coupling make code maintenance and use more convenient, it is not prone to errors.
2.
Do not rush to write code:
After having a general idea in your head, you should immediately break down the code in a "professional" manner. Then, after the general check, the rest will be handed over to the compiler for inspection, so the operation passes, write the following function to hide a large number of dangerous code. Over time, you will be stuck in a big pitfall that you have dug for yourself.
Key: speed is not enough. Every time you type a word, you need to know what you want to input.
3.
Do not trust anyone:
I don't believe anyone who may cause trouble to write the code. These people include: real customers, malicious use (possibly hackers), client code ), running environment (the disk space may be full, the network is disconnected, and so on), external Runtime Library (the external DLL on which the self-written code depends has been removed from the request location ).
4.
The goal of coding is to be clear, not to be concise:
If you choose one from concise (may be confusing) and clear (may be lengthy) code, I think most people will choose clear code, although it is relatively lengthy (after all, the Code is not written on paper bought with silver ).
5.
I don't want others to do what they shouldn't do:
The attribute or method that is designed to prevent others from accessing should be restricted to the class or package as much as possible.
6.
Enable all warnings during compilation
Increasingly developed, powerful compilers will tell us which code is not properly written, which variables are declared unused, and so on, which may bring unexpected results in the actual running environment, we don't know how to fix the code. The warning information after compilation will make our code more robust.
7.
Use a secure data structure:
The most common security risk is buffer overflow. For example, if a buffer has a length of 10, but data with a length of 11 is written to the buffer, other data may be overwritten, this may cause negative effects. Of course, the excellent development platform such as. Net now has CLR to manage memory, which gives us more time and energy to consider what we want to do with code.
8.
Check all returned values:
If a function returns a value, there must be a reason to do so. To check the returned value, if you do not check the returned value, many imperceptible errors will occur. Check the returned value. The returned value may be an error code (CProgramGenerally, the error code is returned. You must identify the code and handle all the errors. If you endure the error, the danger will be quietly penetrated into our program. C # provides an exception mechanism that is thrown out step by step along the stack. We should write C # code, reasonably encapsulate exceptions of different levels (underlying exceptions must reflect the underlying level, for example, dbexception. exceptions of the business layer must reflect exceptions of the business class to productinfoinitialexception ).
9. carefully handle memory and other valuable resources:
These resources include memory, disk files, network connections, and database connections. Haha, now both JVM and CLR can automatically clean up resources and garbage collection. We are so happy, but we should not be too happy, we still need to display the release of the resources we no longer need, after all, JVM and CLR are following a certain mechanism (see http://www.cnblogs.com/anorthwolf/archive/2009/12/07/1618744.html ), we must display the termination of references to objects that are no longer used and will not be automatically cleared. The less advanced garbage collector will be blinded by the circular reference objects.
10. Declare variables as late as possible:
That is, the variable must be declared by using the code snippet closest to the variable.
11. initialize the variable at the position where the variable is declared:
If all variables are initialized, its purpose is clear. "If I don't initialize it, I don't care about it." The empirical principle is false. If a variable is declared in one location, initialized in another location, and used in the third place, once the initialization code is skipped, unexpected results will be obtained. Then we can find the cause again, which is difficult.
12. Be careful with forced type replacement:
Some types can be forcibly converted, but some types will lose some data during the conversion process.
13. provide default behavior:
For example, the switch statement must have a default implementation for default.
14. Check whether the value is online or offline:
In the. NET Framework, some numeric types have range constraints, but if we want to check whether the conditions are met in some business development: for example, the age cannot be negative.
15. constraints:
Constraints mainly include:
1.5.1 prerequisites: before entering a piece of code, it must be true.
1.5.2 post condition: after entering a piece of code, it must be true.
1.5.3 constant condition: the program runs to a specific point and must be true.
1.5.3 assertions: any other statement about the state of the program at a given position.
The specific content is:
Check all array boundaries.
Whether the pointer is cleared before the pointer is abolished.
Ensure the validity of function parameters.
Perform a full check before returning the function result.
The status of the object is consistent before the operation.
To sum up, it is very important to write correct and excellent code, which requires recording all your ideas. This will make the program easier to maintain and reduce errors. Defensive Programming is a way to anticipate and prepare for the worst case. It is a technology that prevents simple errors from becoming hard to find. Using the constraints of code compilation with defensive code will make the program more robust.