Code style

zhaozj2021-02-08  241

Code Style

Code style

1 Introduction

2. What is a style?

3. Why is the style of the code?

4. Less work, more documents?

5. Recommended code style

6. Simple documentation

7. Output style

8. Conclusion

Introduction

Let's face it ... If you are a senior programmer, you always work in the final deadline and your ultimate goal is to complete your design. If you are a novice, your efforts are more research, trials, of course, there are errors and you want your program to run like intended. In any case, when your program is really likely, the success of the success is very exciting, but more programmers find that the pride feel better when generating program internal code with a good style.

If you are a member of the program design group or if you are still writing a school assigned task, you will have the opportunity to be asked to comply with some of the style rules that must be observed. The vast majority of programmers considered that this thing is like a 10-year-old child looks like bed. But senior programmers and the group leaders I have seen and how many styles used to use many styles will try to communicate with some of the skills you have in the same way. In this article I will try to include some views of the output style, which may have help you program.

Less work, more documents?

Therefore, the style means an annotation, right? wrong. If there is no right, the annotation will become a disaster. I still hope that a programmer learns to enter an annotation or really pay more attention to the annotation. For future maintenance, you must force yourself to place an annotation. So how can I not use an annotation?

Obviously, what is the most difficult thing to have a newbie is what is a good variable name. Let's take a look at the following code. Can you tell me what the following code does?

FLOAT __FASTCALL TEXAMPLEFORM :: CalcaveRAGRAMPLEFORM :: CalcaveRagegrade (Void)

{

INT Y = 0;

INT i = 0;

For (i; i

Y = y g [i];

}

Return float (y / x);

}

In the above example, you can easily tell me what is the representative? What is X? This code may require some comments to explain the representative meaning of these variables and what happened in the code? Apply the above code style to see what logical relationship. Now let's take a look at the application better code style, what is the code?

FLOAT __FASTCALL TEXAMPLEFORM :: CalcaveRAGRAMPLEFORM :: CalcaveRagegrade (Void)

{

INT TOTAL = 0;

For (int i = 0; i

{

Total = grades [i];

} // Request all the results

Return float (Total / maxgrades);

} // Calculate average results

When you are in the wrong time, the above two codes are excellent, and you don't have to say more. Let us now discuss some recommended style that makes your code more maintainable.

Recommended code style

1. Use a variable name with the description.

2. Use I, J, K, L, M as the cyclic count variable. This originates from Fortran, which is the fact that this is a fact in fact industrial standards.

3. Note for all statements and methods at closed numbers. This is easier to make decisions when trying to find the previous initial parentheses of this pairing, especially when the statement is long.

4. Consider putting the initial braces of the IF back or cycle defining body on a separate line. This really helps you find the closing brackets corresponding to it.

5. Use the appropriate combination operator ( =, * =, etc.). Use and - operators for self-increasing (self-reduced) variables. Use these operators correctly make your code more readable and more consistent. This also reduces the number of characters input. The combined operator also helps the compiler to generate faster code. For example, the ASM (assembly) code generated by i is inc [i], and i = i 1 will generate the following ASM (assembly) code MOV EAX, [I] Inc Eax MOV [I], EAX. 6. When you annotate the code! If a logical relationship of a piece of code is complicated, the annotation will help others understand the code. However, if the logical relationship is straight, avoiding additional annotations. Maintain your annotations as you maintain your code!

7. When name a variable, use the description meaning. Simple variables (for example, int, long, string) should start with lowercase characters. Complex variables (for example, objects, structures, arrays) should start with uppercase. All words included in the variable name should be on the beginning. This will have a clear first impression that the person who reads (written) code has a clear first impression on the data type accessed.

8. Avoid using underscores in the variable name. It has a special meaning in most compilers.

9. Modularize the code as much as possible (not mad). If reasonable, place the code into the function. This allows for better code reuse and readability.

10. Use the correct loop. If the code is at least once, use the Do-While loop, otherwise you use the While-DO loop. If the exact number of cycles is known, use the for loop.

11. When the number of incidents exceeds two, as long as the Switch declaration is used. At the same time, whenever it is possible to contain a Switch Default (default switch), there will always be a option to be triggered. The Switch declaration is easy to get the wrong, and the speed is faster than the combined multiple IF declaration.

12. Plus a blank line between the logic steps in your code (for example, defining variables, cycles, etc.).

13. It is very important to declare the location of the variable. Variables should be declared to almost no randomness. When the variable is used for the entire (class) object or must be visible outside the object, the variable should be placed in the header file. Temporary variables should be declared within their internal declaration if they do not need to be accessed outside the IF declaration or the cyclic body. Incorrect placement variable declarations can cause slow execution, errors, or cause misleading code.

14. Initialize all variables.

15. If you have a function of non-empty return (with return value), make sure all exit points use Return. Warning "Function Should Return A Value" generated by the compiler (function should return a value) to cause enough attention. This is a serious warning and may result in random errors in your software.

16. When assigning a value between two different types of variables, the variables should be compiled to avoid warnings for the compiler (for example: int x; float y; ... y = float x;). Do you can prevent warnings from "Conversion May Loose Significant Digits". As a programmer, your goal should be reduced as much as possible. Mandatory type conversion will eliminate most of them.

17. Always set the pointer to NULL after deleting.

18. Try to investigate as much as possible to avoid "closed door". The proof function is prioritized from the new code when using the program. This will give you more time to write real logic code and very helpful. Although it is very interesting despite the writing of dynamic linked lists, it has already been completed! 19. The correct spelling is important. If you are missing, the future search will be difficult.

20. Never use two variable names that only have different cases.

21. Enter an annotation when you create a code instead of it. Keep the annotated maintenance when you modify the code.

22. If you annotate (REM) a piece of code when debugging or deactivating, make sure you finally delete the annotated code.

23. The last most important thing is to keep the style.

Simple document

Ordinary documents are very effective in creating a maintenance system. You should set up a standard to place the contents of your documentation. Here is something that should be done in your template:

1. Original name

2. Original creation date

3. File use

4. Includes main content list including use inside

5. A revision history including amendment date. At the same time, the bug found and repaired when revised.

File annotations should be placed in the document header and as far as possible. Below is an example of our current application. This example is more complicated.

/ *

Written by (Author): Scott Cross

Date Originally Completed (Original Date): 9/18/99

Purpose (use):... Main routine for NY Billing This logic calculates the installments and provides all data necessary to print, display, and report billing status The form will display the billing information The main structure, InvoiceInfo, has all information including detail of Installments and Payment activities. Although the main object is a form, the form need not be shown in order to get billing information. This is the only billing logic for this version of the system. All billing inquiries should go through this routine.

Usage (Usage):. Nothing will be performed during the OnCreate event with the exception of setting some reference variables All calculations are done by calling the main routine LoadAcctInfo This routine can be called many times for different policies since it is fully initialized on each. Call. There Area 5 parameters for the main functions and their usage is as follows:

Bool loadAcctinfo

String policyNo - Supplies the logic with the targeted PolicyNo bool printInvoice -. Set to true if you want to print the invoice bool nightRunning -. If being called from the night, set to true bool payableRunning -. If being called by accounting rpt, set to true String masterPrintDate - This is a date For more info on usage, see cpp);... No preliminary logic needs to be performed and the function will return true in most cases No structures are passed since the main structure is public.. IT IS Imperative That The LoadAcctinfo Be Called Prior To Displaying The Screen Or Unexpected Results Can Occur Since The Main Structures Will Not Be Initialized.

struct InvoiceInfoStruct {PaymentHistoryStruct Payments [30]; - Payment History int paymentCount; - Count of Payments InstallmentStruct Installments [30]; - Installment Information int installmentCount; - Count of Installments int currInstall; - The current due installment float totalPaid; - The total paid on file * float totalDue; - Total due on file float pastDue; - Total amount past due float totalBilled; - Total amount billed on file float totalApplied; - Amount applied to installments ** String equityDate; - The date the premium is paid to String Datedue; - date the file is due a payment float annualizedpremium; - the annualized premium ***};

* Restricted to masterprintdate ** surplend Total PAID *** What the annualized premium is for the policy as stored in the tables if rated for one year.

Update History: 09/18/1999 - Scott - Completed02 / 01/2000 - Scott - Fixed TotalPaid Error On Cancelle File * / Output Style

There is no standard in output style. In my concept, the most exciting part of the programming is the design of the program. You can have your own choice, from what is good or bad until the system's appearance and feelings. Despite this, there are still some suggestions for your design.

1. Select a unified font.

2. Design the interface to work normally under different resolutions and different settings. Enable / don't have a big font, then test your software. And assume that the user is still running under the VGA setting of Windows (640x480 16 colors).

3. Test the software under multiple color schemes.

4. Try maintenance of realistic 3D effects. In most cases, the initial Form (page) should be protruded and have an additional concave effect. Although this looks a little pediatric, this makes the program deep and very helpful to split the page.

5. Keep in mind the performance of the output effect. In the loop in the processor set, the more simple, the faster execution.

6. Try to avoid using too much of the head components and effects in the interface. This will give people a feeling, or may hurt the user's confidence, unless the project requires the design of the floating.

7. Design the login screen to get more than the mouse action.

8. Your user may appreciate the uncommorative environment, but also keep in mind that this can rely on the user's configuration, multi-screen may make the system too slow. Try to find a balance between speed and availability.

9. It is suitable to use pop-up prompts and prompts at all times. Remember to set the page from the beginning.

10. Wizard Type The boundary is very suitable when complicated multi-step procedures. This allows the software to guide users to walk through these steps. Find a good Notebook component.

11. When performing long-term operation, Application-> ProcessMessages () should always be called; keep the interface update and let Windows know that your application is still active and can respond to messages.

12. The last most important thing is to keep the system style.

in conclusion

The programming style is more important than most programmers imagined. Do you want other programmers to see the code in your current project? Are you as proud of your code as your system? It is now speaking to decide what style wants to use in your code and start using this style every day. Remember, use a habit to develop a habit of 6 weeks, whether it is good or bad.

good luck!

Original: Scott Cross

Translation: cker

Copyright statement:

On the domestic website, there are many contents about C Builder, but more software, components are mainly. Most of the forum can not be satisfactory, very empty. The book is expensive, but the content is too expensive. For beginners who are insufficient, self-study is not enough, so they want to do our best.

All materials in the article come from foreign websites. Because E text is inconvenient, turn into Chinese. Also because English and computers are not very good, the mistakes in the text are inevitable. If you feel useful, I plan to continue to collect some useful things.

If you have any comments and suggestions, please allow mailto: cker@sina.com

You can copy, distribute, download this document free. However, you may not take it, change this article, or use this article to see any form of interest.

Pacific

2001.2

转载请注明原文地址:https://www.9cbs.com/read-2194.html

New Post(0)