Code Craft: Code Surface
I. Good defense-Defensive Programming Skills for robust code
1. Defensive Programming. Provide some additional input to test whether the code will crash (the correct code will never crash ). 2. Any possible error may occur. Do not make any assumptions. unrecorded ideas will constantly cause defects, especially as the Code grows. 3. The goal of coding is to be clear, rather than concise. complicated structures or uncommon language skills will eliminate the maintainability of code. 4. Keep all variables in the smallest possible range. Do not declare global variables. If the variable can be declared as a local variable in the function, do not declare it in the file range. If the variable can be declared as a local variable in the loop body, do not declare it in the function scope. 5. compiler warnings can capture many silly coding errors and enable them in any situation to ensure that your code can be compiled quietly. 6. Handle the memory with caution. Any resources obtained during execution must be completely released. For example, if A references B and B references A, and no references are made to A and B, the object will never be cleared. This is an undiscoverable form of Memory leakage. 7. Initialize all variables at the declared position. If you accidentally use an uninitialized variable in C/C ++, your program will get different results each time it runs, this depends on the junk information in the memory at that time. 8. perform forced conversion with caution. For example, if you try to convert a 64-bit integer to a smaller 8-bit data type, what about other 56-bit data types? Your execution environment may suddenly throw an exception or quietly degrade your data integrity. 9. Add constraints to the program. ① Check whether all array access is within the boundary; ② assert that the pointer is non-zero before discarding the pointer; ③ ensure that the function parameter is valid; ④ perform a full check before the function returns the result; ⑤ verify that the state of the function is consistent before the operation object.
Ii. Careful Layout-layout and style of source code
1. Various aspects of the Code style (such as the naming conventions of functions and variables) and program structures closely related to them (for example, do not use goto, other coding problems, such as writing only functions at the exit of the portal, determine the programming style. 2. Real readers who know your source code: other programmers. The clearer the code, the better, and the easier it is to fix vulnerabilities. 3. select a good encoding style and stick to it. If your team already has an encoding standard, use this standard instead of your own style. However, do not blindly give up your style. You need to know whether the cost and benefits of doing so are cost-effective. If your company does not have an internal style, push the job and develop a new style... 4. mujial: Say no to it. Do not get involved. Stay away from the right. War is a waste of energy. As a professional programmer, you should break away from these unnecessary arguments. There are a lot of arguments, such as editors, compilers, methodologies, the best language, and so on. These arguments have been going on for many years. They will continue, and no one will win the debate. No one can give the correct answer because the correct answer does not exist. This debate is just an opportunity that a person wants to impose his preferences (though not necessarily effective) on others.
3. Proper Name-give meaningful names to meaningful things
1. Learn how to clearly name things-the name of an object should clearly describe this object. In terms of naming, we should focus on clarity rather than conciseness. However, a short (or even a letter) variable name, that is, a loop counter, can be used. 2. ① name the variable. For a noun, for example, the variable names in a GUI application can be OK _button and main_window, or even those variables that cannot correspond to objects in the real world, you can also assign a noun name, such as elapsed_time or exchange_true. If it is not a noun, a variable is usually a noun verb, such as count. The name of a numeric variable describes its value, for example, widget_length. The name of a logical variable is usually a name in the form of a condition statement. You can naturally determine whether the value is true or false by name. ② Name the function. Do not use words such as be, do, and perform for meaningful function names. For example, what is the function apples? Does it return the number of apples, convert other things into apples, or produce apples? We should hide the specific implementation process inside the function and always name the function from the user's perspective (that is, the function's role-Overview and abstraction ). For example, if a function is used to calculate the number of apples, the name should be countApples (). ③ Name type. Class can describe some stateful Data Objects. In this case, the name may be a noun. It may be a function object (like a function) or class that implements a virtual destroy interface. Here, its name is probably a verb, it may also contain the name of a recognized design pattern. The Interface Class tends to be named based on the functions of the interface, and the names similar to Printable and Serializable are very common. For example, DataObject is a bad name: This class may contain data and is obviously used to create an object-this does not need to be declared repeatedly. Avoid unnecessary words in the name, especially in the type name. Do not use the following words: calss, data, object, and type. ④ Namespace. Assign the name of the logical relationship between the namespace and the package to reflect its content. If the content is part of the library interface, use it as the Library name. If the content is a part of a large system, select a name that describes this part: UI, filesystem, or controls is a good name. Do not select the name of a set that is named repeatedly. controls_group is a bad name. ⑤ Life macro. Macros in C/C ++ are always capitalized to highlight them, and are named carefully to avoid conflicts. Do not use this fully-capitalized name for any other object. Never. It is useful to use a unique file name or project name prefix. The macro name PROJECTFOO_MY_MACRO is safer than MY_MOCRO. ⑥ Name file. For the C/C ++ file of the window definition interface, the name should be widget. h rather than widget_interface.h or other similar variants. Naming files have many subtle but important issues: note that uppercase is not case sensitive for some file systems, but errors may occur when transplanted to platforms that are case sensitive; for some reason, if your file system considers foo. h and Foo. h is two different file names, so do not use it. Make sure that all files you create have different names, even if these files are distributed in different directories, arrange your file so that you can include library_one/version in the file. h and library_two/version. h and other information to avoid confusion.
Iv. Self-explanatory-skills for writing self-document code
1. Do not write code that requires external documentation support. Such code is fragile. Make sure that your code is clearly read. 2. Use existing language functions as much as possible to describe constraints or behaviors. For example, if you want to define a value that never changes, force it to be defined as a constant type (using const in C). If a variable should not contain negative values, use an unsigned type (if your language provides this type), use enumeration to describe a set of related values, and select an appropriate type, in C/C ++, put the value into the size_t variable, and put the operation result of the pointer into the ptrdiff_t variable. 3. Named constants. Code such as "if (counter = 76)" can be confusing, and it hides the meaning. if like the following const size_t bananas_per_cake = 76 if (count = bananas_per_cake) {// make vanilla cake}, it will be much clearer, and if you need to use the constant 76 multiple times in the code, you only need to modify one.
5. Additional comments-how to write code comments
1. Writing well-written code does not actually require comments, because each line of code can be self-explanatory. Function names such as f () and g () will scream and ask for comments to describe them, but function names such as someGoodExample () do not need to be commented at all. 2. Good comments explain why (The purpose of the Code), not how (the code process ). 3. Follow the golden rule: a fact-a source. Do not repeat the code in comments. For example, ++ I; // increment i4. When you find yourself writing a dense comment to explain your code, stop it. Remember what you are doing first, and then consider whether you can change the code or algorithm to make it clearer. 5. Do not include the code to be excluded in comments, which can be confusing. Use the C language "# ifdef ()... # endif "or an equivalent function. These function blocks are nested with each other and have a clearer meaning (especially when you forget to come back and organize the Code ). 6. Annotations can also be used as embedded symbols in the code, you can see that "// XXX", "// FIXME", or "// TODO" are scattered in unfinished files, it is best to let the program throw an exception (or debug () so that it is not easy to forget to complete the missing code. 7. Comments are outdated. Trust the code and suspect comments. Maintain all comments around the code when you modify the code.
6. People are not sages-handling inevitable situations-errors in code
1. Errors May and will inevitably occur. Almost any operation will bring unexpected results. This result is different from the bug in the defective program, because you know in advance that the error will happen. For example, the database file you want to open may have been deleted, and the disk space may be used up at any time, so that you cannot store any content, or the Web server you want to access is currently unavailable. 2. Where did the error come from. Errors can be classified into three types: ① user errors. The user may provide incorrect input or attempt to perform absurd operations. A good program will point out the error and help the user correct it, for example, the system prompts the user to enter something. ② the programmer's error indicates that the code is correct when the user presses the button or crashes. This is a code defect of the programmer. You can use the return value to check for possible errors; ③ In an unexpected situation, the buttons pressed by the user are correct, and the programmer has not made any mistakes. However, due to the teasing of the god of destiny, we may encounter something that cannot be avoided, maybe the network connection has failed, the printer ink is used up, or there is no available hard disk space. We can pop up a message box when an error is detected to notify the user, or send an automatic signal to the client code when the middle-Layer Code detects an error. 3. Error Reporting mechanism. You can immediately stop the program when you encounter problems, which is easier than handling errors everywhere in the code, but it is not a good engineering solution. The following mechanisms are available: ① return value (bool return value, A more advanced method is to list all possible exit states and return a corresponding cause code. A value indicates that the other values are successful, indicating different exceptional termination conditions respectively) and ② error status variables (not recommended. Set a shared global error variable to view this variable after calling the function), ③ exception capture, and ④ signal. The use of the Error Reporting mechanism depends on the architecture. Java and C # tend to use exceptions. C ++ can choose to discard exceptions so that they can be transplanted to platforms that do not support exceptions or interfaced with earlier C languages. 4. handle errors. Logs, recording in detail all the errors you encounter in program logs, and collecting relevant information; reports, user experience records; recovery, if an error is encountered, upload the error for help without knowing how to solve it. If the problem is ignored, this is the method of error. If the lower-level function call fails, clear the error report and spread it upwards. 5. Your code will inevitably encounter some errors that must be cleared by the user. If you want to prompt the user to solve the problem, you should first have some general ideas: ① users do not think like programmers, so they present information in the way they expect; ② ensure that your messages are not uncertain; ③ do not present meaningless error codes, for example: no user knows what to do when facing "Error code 707E"; ④ separate serious errors from warnings; ⑤ ask questions only when the user fully understands the consequences of each choice (even if "continue?" Such a simple question ). 6. question to consider: ① whether the cleaning is appropriate and reliable code will not leak resources even when an error occurs; ② do not disclose inappropriate information to the outside world in the error report; ③ correct use exceptions, follow language rules to prevent abuse; ④ if an error that should not occur during the normal execution of a program is tracked, Use assertions. ⑤ The earlier the error is found and corrected, the less trouble it will cause; ⑥ it is almost impossible for people to ignore your mistakes. If there is a chance, someone will use your code maliciously, or it may be accidental input. 7. Be careful with the following errors: ① check all function parameters; ② check whether the constant conditions at the key points are met during execution; ③ check its validity before using any external value; ④ check the return status of all system calls and other lower-level function calls.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.