C # Coding specifications and good programming habits

Source: Internet
Author: User

Everyone will 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. tow.timestring ();
MessageBox. Show (message );
If (...)
{
// Do something
//...
Return false;
}
Return true;
}

This code looks better than above ::

Bool SayHello (string name)
{
DateTime currentTime = DateTime. Now;
String message = fullMessage + ", the time is:" + currentTime. tow.timestring ();
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 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 "PlainText ":
// 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. But if the code is not clear, you can

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.