C # coding specifications and programming good habits

xiaoxiao2021-03-06  118

Written: dotNetspider.com (http://www.dotnetspider.com)

Translation: Yang Hehong

No one will write the code! Monthly programming experience allows you to write "running applications." Let it run easy, but you need more effort to coding more efficiently!

You know, most of the programmers are writing "running code," instead of "efficient code". We mentioned before this guide course. Do you want to be your company "the most distinguished professionals"? Write "Efficient Code" is an art, you have to learn and practice it.

Name customs and specifications

Note: Pascal case - all words first letter uppercase, other letters lowercase. Camel case - except for the first word, all words first letters, other letters lowercase.

Class name Using Pascal Size Public Class HelloWorld {...}

Method Using Pascal Size Public Class HelloWorld {Void Sayello (String Name) {...}}

Variables and method parameters use CAMEx case

Public class helloworld {int totalcount = 0; void systo (string name) {string fullmessage = "hello" name; ...}} Do not use Hungarian methods to name the variable

Previously, most programmers like it - put the data type as the prefix of the variable name and M_ as the prefix of the member variable. E.g:

String m_sname; int nage;

However, this approach is not recommended in the .NET coding specification. All variables are written in a Camel case instead of data type and m_ to perform prefix.

Name variables with meaningful, descriptive words

- Don't use abbreviations. With NAME, Address, Salary, etc., addR, Sal - other variables I, N, X, etc., using individual letters. Use Index, Temp, etc. Variable exceptions for loop iteration: for (int i = 0; i < COUNT; I ) {...}

If the variable is only used for iterative counts, there is no other place in the loop, and many people still like the variables (i) of a single letter, not additional names. - Underline is not used in the variable name (_). - Naming space needs to be named according to standard mode

...

File name and class match

For example, for class HelloWorld, the corresponding file name should be HelloWorld.cs (or, HelloWorld.vb) indentation and intervals into Tab. No Spaces .. Note Necessary and code alignment .. The curled arc ({}) needs to be aligned with the code outside the parentheses.. Use an empty line to separate the logical grouping of the code. .

bool SayHello (string name) {string fullMessage = "Hello" name; DateTime currentTime = DateTime.Now; string message = fullMessage ", the time is:" currentTime.ToShortTimeString (); MessageBox.Show (message); if (...) {// do something;} Return true;} This code looks better than the above: (String name) {String FullMessage = "Hello" Name; DateTime CurrentTime = DateTime.Now; String Message = FullMessage ", The Time IS:" CurrentTime.toshostTimeString (); MessageBox.show (Message); if (...) {// do something // ... return False;} Return True;} In a class, each method needs to use a holiday, and can only be separated. The sputum must be independent, not like if, for, etc. can be in the same line with parentheses. Good: if (...) {// do something} is not good: if (...) {// do something}

Skated in front of each operator and parentheses. .

Good: if (showresult == True) {for (int i = 0; i <10; i ) {//}}

No good: if (showresult == true) {for (INT i = 0; i <10; i ) {//}}

Good programming habits

Comply with the following good habits to write a good program

Avoid using big files. If the code in a file exceeds 300 ~ 400 lines, you must consider separating the code to a different class. Avoid writing too long. A typical method code is between 1 to 25 rows. If a method is more than 25 lines, it should be considered to decompose it to a different method. The method name needs to see what it works. Don't use the name that will cause misunderstandings. If the name is at a glance, there is no need to use a document to interpret the functionality.

Good: void SavephoneNumber (String Phonenumber) {// Save the Phone Number.}

Well: // this method will save the phone number. Void Savedata (String Phonenumber) {// save the phone number.}

A method only completes a task. Do not combine multiple tasks into a method, even those tasks are very small.

Good:.. // Save the address SaveAddress (address); // Send an email to the supervisor to inform that the address is updated SendEmail (address, email); void SaveAddress (string address) {// Save the address /. / ...} void sendemail (string address, string email) {// send an email to inform the supervisor what the address is change. // ...} Well: // save address and send an email to the supervisor TO INFORM THATDRESS (Address, Email); Void SaveAddress (String Address, String Email) {// Job 1. // Save The Address. // ... // Job 2. // send ann Email to Inform The Supervisor That The Address Is Changed. // ...}

Use the unique type of C # or VB.NET, not the alias type defined in the System namespace.

Good: int Age; string name; Object ContactInfo;

Not well: INT16 AGE; String Name; Object ContactInfo; Do not use fixed values ​​in the program, replaced with constants. Don't use string constants. Use resource files. Avoid using many member variables. Declare a local variable and pass to the method. Do not share member variables between methods. If you share a member variable between several methods, it is difficult to know which method is when it modifies its value. Use enum when necessary. Don't use a number or string to indicate the discrete value. Good: enum MailType {Html, PlainText, Attachment} void SendMail (string message, MailType mailType) {switch (mailType) {case MailType.Html: // Do something break; case MailType.PlainText: // Do something break; case MailType .Attachment: // do something break; default: // do something Break;}}

Well: void sendmail (String Message, String MailType) {Switch (MailType) {CASE "html": // do something "plaintext": // do something ": attachment": // do Something Break DEFAULT: / / do Something Break;}} Don't declare the member variable as public or protected. Declare the use of public / protected's Properties with Private. Do not use specific paths and drive names in your code. Use the relative path and make the path programmable. Always think about your code is running in "C:". You won't know that some users are running in the network or "z:" disk. Some "self-test" when the application starts and make sure the required files and attachments are in the specified location. Check the database connection if necessary. Any problem occurs gives the user a friendly tip. If the required configuration file cannot be found, the application needs to create one of the default values. If the error value is found in the configuration file, the application will throw an error and give the prompt message to tell the user correct value. Error messages need to help users solve the problem. Don't use an error message such as "Application Error" and "Find an Error". And should be an iconic "Update the database failed. Make sure that the login ID and password are correct." The specific message. When the error message is displayed, the user should be prompted to solve the problem. Don't use the "Update Database Failed." This kind of prompts how to do: "Update the database failed. Make sure that the login ID and password are correct." Show to the user is short and friendly. But you have to record all possible information to help diagnose problems. Tell your code, each line of code, each declared variable is noted. Note in the required place. The ability to readability requires little annotation. If all the variables and methods naming is meaningful, it will make the code readability and there is no need much notes. An annotation that does not have a lot of lines makes the code elegance. But if the code is unclear, readable, it is bad. If a complicated hard principle should be used for some reason, a good document and reporting of the program are available. The value of a numerical variable is not 0, -1, etc., gives the reason for the selection of this value. In short, you have to write a clear, readable code, can be understood without any notes. Spell check the comment to ensure the correct use of grammar and punctuation. Unusual treatment should not "capture an exception but nothing." If you hide an exception, you will never know that the abnormality has occurred. When an exception occurs, give the friendly message to the user, but to accurately record all possible details, including the time, and related methods, class names, etc. Only capture specific exceptions, not general exceptions.

Good: void readfromfile (string filename) {Try {// read from file.} Catch (fileioException ex) {// log error. // re-throw exception depending on your case. Throw;}}

Not good: void readfromfile (string filename) {Try {// read from file.} Catch (exception ex) {// catching general exception is Bad ... we will never knowledge {/ WAS a file error or some} Error. // Here You are Hiding an Exception. // in this case no one will service. Return "";}} Do not have to capture general exceptions in all methods. No matter it, let the program crash. This will help you discover most errors in the development cycle. You can use the application level (thread level) error handler to process all general exceptions. When you encounter an "general error", this error processor should capture an exception, give the user prompt message, record the error message before the application shutdown or the user selects "ignore and proceed". Do not have to use try-catches every method. It may only be used when a particular exception can occur. For example, when you write a file, handle the exception fileioException. Don't write too much TRY-CATCH module. If necessary, write a separate TRY-CATCH module for each executed task. This will help you find which code produces an exception and give the user a specific error message if the application needs, you can write your own anomaly. Custom exception should not be derived from the base class systemException, but to inherit. IapplicationException.

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

New Post(0)