C # Coding specifications and good writing habits

Source: Internet
Author: User
Anyone can write Code ! A few months of programming experience allows you to write "runable Applications ". It is easy to run, but coding in the most efficient way requires more effort!
You know, most programmers are writing "executable code" instead of "efficient code". As we mentioned above, do you want to be the "most distinguished professional" of your company? Writing "efficient code" is an art. You must learn and practice it.

Naming Conventions and specifications

Note:
Pascal case-the first letter of all words is in upper case, and the other letters are in lower case.
Camel case-except the first word, the first letter and other letters of all words are in upper case.

Class Name in Pascal case
Public class helloworld {...}

Method Pascal case
Public class helloworld {void sayhello (string name ){...}}

Variables and method parameters are in the camel case-sensitive format.

Public class helloworld {int totalcount = 0; void sayhello (string name) {string fullmessage = "hello" + name ;...}}
Do not use the Hungary method to name variables

In the past, most programmers liked it-taking the data type as the prefix of the variable name and M _ as the prefix of the member variable. For example:
String m_sname; int Nage;
However, this method is not recommended in. Net encoding specifications. All variables are in the camel case format, instead of using the Data Type and M _ as the prefix.

Use meaningful and descriptive words to name variables

-Do not use the abbreviation. Use name, address, salary, and so on to replace Nam, ADDR, Sal
-Do not use single-letter variables such as I, n, x. Use index, temp, etc.
Variable exceptions used for loop iteration:
For (INT I = 0; I <count; I ++ ){...}
If a variable is used only for iterative counting and does not appear elsewhere in the loop, many people prefer to use a single letter variable (I) instead of another name.
-The variable name does not contain underscores (_).
-The namespace must be named in standard mode.

...

The file name must match the class name.

For example, for the class helloworld, the corresponding file name should be helloworld. CS (or, helloworld. VB)
Indentation and interval
Indent with tab. Do not use spaces ..
The annotation must be aligned with the code ..
The curly arc ({}) must be aligned with the code outside the brackets ..
Use a blank line to separate the logical grouping of 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 false;} return true ;}
This code looks better than above ::
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 false;} return true ;}
In a class, each method requires an empty row, or only one row can be separated.
The Arc should be an independent line, unlike if, for, and so on ..
Good:
If (...) {// do something}
Bad:
If (...) {// do something}
Each operator and parentheses have a space ..

Good:
If (showresult = true) {for (INT I = 0; I <10; I ++ ){//}}
Bad:
If (showresult = true) {for (INT I = 0; I <10; I ++ ){//}}
Good Programming habits

Follow the following good habits to write a good program

Avoid using large files. If the code in a file exceeds 300 ~ Line 3: Separate the code into different classes.
Avoid writing too long. A typical method code is in the range of 1 ~ Between 25 rows. If a method sends more than 25 lines of code, you should consider breaking it into different methods.
The method name must be able to see what it does. Do not use a name that may cause misunderstanding. If the name is clear, you do not need to use documents to explain the functions of the method.

Good:
Void savephonenumber (string phonenumber) {// Save the phone number .}

Bad:
// This method will save the phone number. Void savedata (string phonenumber) {// Save the phone number .}
One method only completes one task. Do not combine multiple tasks into one method, even if 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 that the address is changed. //...}

Bad:
// 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 that the address is changed. //...}
Use the special type of C # Or VB. net instead of the alias type defined in the system namespace.

Good:
Int age; string name; object contactinfo;

Bad:
Int16 age; string name; object contactinfo;
Do not use a fixed value in the program, instead of a constant.
Do not use string constants. Resource source file.
Avoid using many member variables. Declare local variables and pass them to methods. Do not share member variables between methods. If a member variable is shared among several methods, it is difficult to know which method modifies its value.
Use Enum if necessary. Do not use numbers or strings to indicate discrete values.
Good:
Enum mailtype {HTML, plaintext, attachment} void Sendmail (string message, 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 ;}}

Bad:
Void Sendmail (string message, string mailtype) {Switch (mailtype) {Case "html": // do something break; case"
(Click a thumbnail to view the larger image)
Laintext ": // do something break; Case" attachment ": // do something break; default: // do something break ;}}
Do not declare the member variables as public or protected. Are declared as private and use the properties of public/protected.
Do not use the specific path and drive name in the code. Use relative paths and make the paths programmable.
Never imagine that your code is running on the "C:" disk. You don't know, some users run programs on the network or "Z:" disk.
When the application starts, perform "self-check" and ensure that the required files and attachments are in the specified location. Check the database connection if necessary. If any problem occurs, give the user a friendly prompt.
If the required configuration file cannot be found, the application must be able to create one by default.
If an error value is found in the configuration file, the application will throw an error and a message will be prompted to tell the user the correct value.
The error message must help you solve the problem. Never use error messages such as "application error" and "discover an error. Instead, it should be given as "failed to update the database. Make sure that the logon ID and password are correct. .
When an error message is displayed, in addition to the error message, you should be prompted about how to solve the problem. Do not use the image "update database failed. "In this case, you need to prompt the user how to do it:" updating the database failed. Make sure that the logon ID and password are correct. "
The message displayed to the user must be short and friendly. However, all possible information should be recorded to help diagnose the problem.
Note
Every declared variable is annotated.
Comment in the desired place. The readable code requires few comments. If the names of all variables and methods are meaningful, the code will be highly readable without too many comments.
Comments with few lines will make the Code look elegant. However, if the code is not clear and the code is not readable, it will be bad.
If complex and difficult principles are used for some reason, the program should be well documented and reposted.
Initialize a value variable with a value other than 0 or-1. The reason for choosing this value is given.
In short, you need to write clear and readable code so that you can understand it without any comments.
Check the spelling of comments to ensure correct use of syntaxes and punctuation marks.

Exception Handling
Do not "catch exceptions but do nothing". If an exception is hidden, you will never know whether the exception has occurred.
When an exception occurs, a friendly message should be provided to the user, but all possible details of the error should be recorded precisely, including the time when the error occurred, related methods, and class names.
Capture only specific exceptions, rather than general exceptions.

good:
void readfromfile (string filename) {try {// read from file .} catch (fileioexception ex) {// log error. // re-throw exception depending on your case. throw ;}< br> poor:
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 ever know that an exception happened. Return ";}}< br> you do not have to capture general exceptions in all methods. Whatever it is, let the program crash. This will help you find most errors during the development cycle.
you can use an application-level (line-level) Error processor to handle all common exceptions. In the case of an "other general error", the error processor should capture the exception and send a message to the user to record the error message before the application is closed or the user selects "ignore and continue.
try-catch is not required for each method. It is used only when a specific exception may occur. For example, when you write a file, handle the exception fileioexception.
do not write too many try-catch modules. If necessary, write a separate try-catch module for each executed task. This will help you find out which code generates an exception and send a specific error message to the user
If the application needs it, you can write your own exception class. Custom exceptions should not be derived from the base class systemexception, but must inherit from. iapplicationexception.

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: info-contact@alibabacloud.com 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.