Part 3 of the Microsoft Software Implementation Technology Course Series: Project in C ++ coding practice

Source: Internet
Author: User
Project in C ++ coding practice

In the practice of C ++ programming, there are usually some defects that affect program performance, efficiency, and localization. Some of these defects are listed below for your reference, and give some suggestions on the defect correction, and give priority to the defect search based on the extent of the impact caused by the defect, 1★The priority is the lowest. 1 Prompts in the programThe prompt information in the program is mixed with the code of the program. Priority of defect search:★Note: writing the prompt information in the program directly in the code will be detrimental to the localization of the program. For example, if the prompt information of the program is in English and written in the CPP file, after compilation, you cannot tell which are the code and which are the prompt information, which makes it very inconvenient to compile the program. The solution is: If you use VC ++ for programming, you can put all the string constants used in the program into the string table of the resource file. When using string table, you can use cstring: loadstring (NID) to load data from the resource file. If you need to perform Chinese conversion, you only need to translate the prompt information in the string table into Chinese. If you do not use VC ++ to develop programs, you can put these string constants in a text file. In Chinese, you only need to normalize the content in this text file. In addition, mixing the prompt information and code in the program will add errors in the program, which is not conducive to program modification. Separating program code from prompt information can reduce the number of errors when writing large software. 2. Retrieving input informationWhen obtaining input information, you must specify a buffer for receiving input. Using a buffer directly to store input information is a defect. Priority of defect search:★★Note: If you do not judge or limit the input length, the buffer overflow may occur, which may cause system crash. 3. I/O OperationThe operation results are not checked during I/O operations. Priority of defect search:★★NOTE: If I/O operation results are not checked, exceptions caused by I/O may cause program crashes and user dissatisfaction. For example, if you want to open a file, but do not make a judgment on the file, if the file does not exist or you do not have the permission to use the file, the program will encounter an exception. 4. Constants used in the programDirectly use the constant value in the program. Priority of defect search:★★Note: a large number of constant values embedded in the program make it difficult to maintain the program, and it also brings difficulties to program debugging. The best way is to define a constant variable Const. 5. cout Medium efficiencyWhen cout output is used, a large number of Endl lines are used. Priority of defect search:★Note: When cout outputs data to a standard device, it corresponds to a memory buffer. The use of Endl clears the buffer. frequent use of Endl reduces the program efficiency and should be written as "\ n ". 6. Functions that may fail the operationFor functions that may fail the operation, do not check the operation results. Priority of defect search:★★Note: For example, if a memory segment is allocated, the required memory space may not be allocated. This potential operation fails without any check. Continuing the program may cause exceptions or even crashes. Make sure to judge all potential operation failures. 7. Include And namespace AbuseDuplicate files, namespaces, or unnecessary files. Priority of defect search:★Note: the repeated use of include and namespace is a defect, that is, the use of multiple times or the use of places that should not be used is blind. For example, a class has already included "iostring. H ", again in. include "iostring. H "to include. if the H file is repeated several times, a repeated class definition error may occur in the program. Even if there is no error, it will also cause name contamination and increase the compilation cost. The so-called pollution refers to a change that may occur in one place when cross-include operations are performed, and the change in another place is forgotten. In this way, the program may have problems. Similar to using the paradigm in databases to eliminate data redundancy, programs must also avoid data redundancy. 8. Improper inheritanceConsider the use of other class functions as an inheritance. Priority of defect search:★★★Note: The use of inheritance relationships does not necessarily reflect the relationship between classes, and sometimes may lead to confusion in the program structure. The inheritance relationship can be used only when it is-. If you only use the function of another class, it is inappropriate to define the relationship between the class and the class as inheritance. In this case, it is the relationship between has-a, or the relationship between the whole and the part. Misuse of inheritance will only lead to confusion of the class relationship. In addition, the misuse of the inheritance relationship may lead to another problem, such as class X {Y;}, which usually occurs in X. # include "Y. H ", so that Class X is tightly coupled with class Y. After the program is completed, if you change Y, that is, Y. H changes, which will inevitably lead to X. H also changes, which leads to all include "x. H "files have also changed, causing a series of chain reactions. The current compiler usually uses incremental compilation, that is, only the part of the file that has been modified is compiled. Therefore, even if only y. A small part of the content of H will also cause a large number of file changes, and the compiler will compile these many changed files, which will consume a lot of time. To. avoid include "Y. H "solution: class Y; Class X {y * Y; // y is the pointer of Y, which occupies 4 bytes X () {Y = New Y ;}} here we will describe that the form of y * y must be used. Otherwise, problems may occur when using y directly. Because every time an X instance is generated, the compiler allocates memory space for X, and it also needs to know how much space the instance y occupies. To know how big y is, you must know the definition of Y. Therefore, you must include "Y. H. This program uses a pointer. In Windows, the pointer occupies only four bytes, And the compiler always knows how much memory should be allocated to X, therefore, you only need to know that Y is a class and does not need to know the specific definition of Y. Back to the above question, why is it easy to create problems when defining inheritance, because inheritance actually places a base class instance on the top of the instance of the derived class, such as: Class X: public y {// for a base class instance, you must allocate space to the base class (Y ;)......} Since you want to put a base class instance, only when you know the size of the instance can you allocate memory to the instance of the derived class, which is equivalent to the above. Therefore, using the inheritance relationship will cause the include "Y. H ", and this will inevitably lead to the above problems, which is also a shortcoming of object-oriented development methods. A major difference between component-oriented software development methods and object-oriented software development methods lies in the fact that component-oriented software development methods discard a problem in object-oriented software development methods, it is the complex inheritance relationship that makes the program tightly coupled. The component-oriented development method defines a clear interface for each component, and interfaces are used for interaction between components, so the coupling degree is very low. 9. Loss of error informationThere is no detailed record of the cause of the error in the program, or the value is simply used to indicate the error information, leading to the loss of the error information. Priority of defect search:★Note: Keep the error details to better find the cause of the error. In addition, you can easily reproduce the error based on the detailed information when an error occurs. Therefore, when an error occurs in each program, a precise error code should be returned, which is conducive to debugging and maintenance. 10. Type conversionUse a C-style forced type conversion. Priority of defect search:★★Note: Forced type conversion in the C style, such as (INT) variable name, is difficult to locate in this form of type conversion, and is not conducive to finding forced type conversion in the code, this reduces the maintainability of the program. The mandatory type conversion operators static_cast, dynamic_cast, const_cast, and reinterpret_cast provided by C ++ should be used. In this way, the cast keyword can easily find the place where type conversion occurs in the program. 11. Select a typeThe data type is not defined based on the true value range of the data, and an inappropriate data type is used. Priority of defect search:★★Note: For example, the int type is used to define the age, but the age does not show negative numbers. This expands the data value range and wastes storage space. It also increases the complexity of Data Validity judgment. 12. Definition of RedundancyDefine Redundant defect search priorities for data types and constants:★Note: redundant definitions of data types and constants will make maintenance difficult. For example, the data type of the template class is generally defined as type <sub_type> I, so that it should be defined as Type Def type <sub_type> X, which will be defined by X each time it is used. 13. Redundant codeThe same Code that completes the same function appears multiple times. Priority of defect search:★★Note: Do not write the same operation twice in the program. This increases the possibility of program errors and is not conducive to program maintenance. 14. Memory Allocation and recoveryA large amount of work that causes memory allocation and recovery, such as new, delete, copying objects. Priority of defect search:★★★Note: memory allocation is very time-consuming. A large amount of use will cause low program efficiency. For example, do not dynamically apply (new) a small memory every time in the program. If you know that the memory space you may need is large, you can apply for a large memory at a time. 15. Values used in the programIn a program, a number is used directly when some numeric values are required to control the process of the program. Priority of defect search:★★Note: the direct use of numbers will make the program difficult to understand and maintain. For example, a statement like for (I = 1; I <10;) is not very good. It should be written as follows: const maxnum = 10; for (I = 1; I <maxnum;) because if numbers are directly used everywhere in the program, it is very difficult to modify them. 16. Data Structure SelectionAn inappropriate data structure is selected. Priority of defect search:★Note: selecting an inappropriate data structure will affect the program's efficiency and prolong the running time of the program. 17. Prefix or suffix?Use a suffix expression when both the prefix and suffix auto-increment can meet the requirements. Priority of defect search:★Note: the efficiency of using a suffix expression is not high, because a temporary variable is generated in the suffix expression operation, and this temporary variable takes additional time and overhead.
Related Article

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: 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.