C # coding specifications and programming good habits

zhaozj2021-02-16  113

C # coding specification and programming good habits: dotNetspider.com (http://www.dotnetspider.com)

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

Mark

:

Pascal case -

All words first letter uppercase, other letters lowercase.

Camel

Case - In addition to the first word, all words first letters, other letters lowercase.

Class name Using Pascal Size PUBLIC CLAS HelloWorld

{

...

}

Method uses Pascal case PUBLIC CLASS HELLOWORLD

{

Void Sayhello (String Name)

{

...

}

} Variables and method parameters use Camel case PUBLIC CLASS HELLOWORLD

{

INT TOTALCOUNT = 0;

Void Sayhello (String Name)

{

String FullMessage = "Hello" Name;

...

}

}

Do not use the Hungarian method to name the variable, 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. Use meaningful, descriptive words to name variables - do not 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 (_). - Namespace needs to be named according to standard mode ...

File name and class matching, for example, for class HelloWorld, the corresponding file name should be HelloWorld.cs (or, helloworld.vb) indent and intervals 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.TOSHORTTIMESTIMESTRING ();

Messagebox.show (Message);

IF (...)

{

// do something

// ...

Return False;

}

Return True;

}

This code looks better than the top :: bo a s (string name) {

String FullMessage = "Hello" Name;

DateTime CurrentTime = datetime.now;

String Message = FullMessage ", The Time IS:" CURRENTTIME.TOSHORTTIMESTIMESTRING ();

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

}

No 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 good procedures to 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.

// ...

}

No good: // save address and send an email to the supervisor to inform That the address is updated.

Saveaddress (address, email); Void Saveaddress (String Address, String Email)

{

// Job 1.

// Save the address.

// ...

// job 2.

// send an email to inform the supervisor what the address is change.

// ...

}

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;

Don't use a fixed value 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;

}

}

Not well: void sendmail (String Message, String MailType)

{

Switch (MailType)

{

Case "html":

// do something

Break;

Case "PlainText":

// do something

Break;

Case "attachment":

// do something

Break;

DEFAULT:

// do something

Break;

}

} Don't declare the member variables 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. Note Don't have a 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 well: void readfromfile (String filename)

{

Try

{

// read from file.

}

Catch (Exception EX)

{

// catching general Exception is Bad ... We will never know WHETHER IT

// Was a file error or some Other Error.

// Here you are hiding an exception.

// in this case no one will no know what an exception happened.

""; "

}

}

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

New Post(0)