C # Coding specifications and good writing habits

Source: Internet
Author: User
Tags object bool exception handling net variables string variable throw exception

Anyone can write code! A few months of programming experience allows you to write "Running applications." Make it easy to run, but coding in the most efficient way requires more effort!
You know, most programmers are writing "run code," not "efficient code." We mentioned earlier in this guide course, do you want to be your company's "Most distinguished professional"? Writing "Efficient Code" is an art that you must learn and practise.



Naming conventions and specifications


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


Class name using Pascal case
public class helloworld{...}


Method uses Pascal capitalization
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 Hungarian methods to name variables

In the past, most programmers liked it-to prefix a variable name with a data type and m_ as a member variable. For example:
String M_sname;int nage;
However, this way in. NET coding specification is not recommended. All variables are prefixed with camel, rather than data types and m_.

Use meaningful, descriptive words to name variables

-Don't use abbreviations. Replace Nam, addr, Sal with name, address, salary, etc.
-Don't use a single letter variable like I, n, x, etc. use index, temp, etc.
Variable exception for loop iteration:
for (int i = 0; i < count; i++) {...}
If a variable is used only for iteration counts, not elsewhere in the loop, many people prefer to use a single letter variable (i) instead of another name.
-Underline (_) is not used in the variable name.
-namespaces need to be named in standard mode

...


FileName to match class name

For example, for class HelloWorld, the corresponding file name should be HelloWorld.cs (or, Helloworld.vb)
Indentation and Spacing
Indent TAB. No spaces.
Comments need to be aligned with the code ...
The curly bracket ({}) needs to be aligned with the code outside the brackets ...
Separate the logical groupings of your code with a blank line ...

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 the 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 a blank line and can only be separated by one row.
The curly brackets need to be separate lines, unlike if, for, and so on, in the same line as parentheses ...
Good:
if (...) {//Do something}
Not good:
if (...) {//Do something}
Empty one space before and after each operator and parenthesis ...

Good:
if (Showresult = = True) {for (int i = 0; i < i++) {//}}
Not good:
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 the 300~400 line, you must consider separating the code into different classes.
Avoid writing too long a way. A typical method code is between 1~25 lines. If a method sends more than 25 lines of code, you should consider splitting them into different methods.
The method name needs to be able to see what it does. Don't use names that can cause misunderstanding. If the name is clear, there is no need to use documentation to explain the function of the method.

Good:
void Savephonenumber (String phonenumber) {//Save the phone number.}

Not good:
This method would save the phone number. void SaveData (String phonenumber) {//Save the phone number.}
One method completes only one task. Don't 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 this is updated. SendEmail (address, email); void Saveaddress (string address) {//Save the address.//...} void SendEmail (string address, string email) {//S End a email to inform the supervisor this is changed. // ... }

Not good:
Save address and send a email to the "supervisor to inform" this is updated. Saveaddress (address, email); void Saveaddress (string address, string email) {//Job 1.//Save the address.///...//Job 2.//Send an email to Form the supervisor is changed. // ... }
Use C # or VB. NET, rather than the type of aliases defined in the System namespace.

Good:
int age; String name; Object ContactInfo;

Not good:
Int16 age; String name; Object ContactInfo;
Do not use fixed values in the program, instead of constants.
Do not use string constants. Use resource files.
Avoid using many member variables. Declare a local variable and pass it to the method. Do not share member variables between methods. If you share a member variable among several methods, it is hard to know which method changed its value at what time.
Use an 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) {CA SE mailtype.html://do something break; Case Mailtype.plaintext://doing something break; Case Mailtype.attachment://doing something break; Default://do something break; } }


Not good:
void SendMail (String, string mailtype) {switch (mailtype) {case "Html"://does something break; case "Laintext "://do something break; Case "Attachment"://does something break; Default://do something break; } }
Do not declare member variables public or protected. are declared private and use public/protected properties.
The specific path and drive name are not used in the code. Use a relative path and make the path programmable.
Never assume that your code is running on the "C:" Disk. You don't know, some users run programs on the network or "Z:" Disks.
The application starts with a "self-test" and ensures that the required files and attachments are in the specified location. Check the database connection if necessary. Give the user a friendly hint of any problems.
If the required configuration file is not found, the application needs to be able to create a copy of its own using default values.
If an error value is found in the configuration file, the application throws an error, giving a prompt message telling the user the correct value.
The error message needs to be able to help the user solve the problem. Never use an error message like "Application Error", "Find an error", and so on. Instead, give the image "update database failed." Please make sure the login ID and password are correct. "The concrete message.
When you display an error message, you should also be prompted to resolve the problem, except where you said it was wrong. Do not use the image "update database failed." "So, to prompt the user how to do this:" Failed to update the database. Please make sure the login ID and password are correct. "
Messages displayed to the user are brief and friendly. But write down all the possible information to help diagnose the problem.
Comments
Do not each line of code, each declared variable is commented.
Comment where needed. Code that is readable requires very little comment. If all the variables and methods are named in a meaningful way, it makes the code very readable and does not require too many annotations.
A comment with a few lines makes the code look elegant. But if the code is not clear and the readability is poor, that's bad.
If you should use complex and abstruse principles for some reason, have a good document and a heavy comment for the program.
A numerical variable is initialized with a value that is not 0,-1, and the reason for selecting the value is given.
In short, write clear, readable code that is understandable without any comment.
Make spelling checks on annotations to ensure proper use of grammar and punctuation.

Exception handling
Do not "catch the exception and do nothing". If you hide an exception, you will never know if the exception has happened.
When an exception occurs, give a friendly message to the user, but accurately record all possible details of the error, including the time of occurrence, the associated method, the class name, and so on.
Catch only specific exceptions, not general exceptions.

Good:
void ReadFromFile (String fileName) {try {//read from file.} catch (Fileioexception ex) {//Log error.//Re-throw Exception depending on the your case. Throw } }
Not good:
void ReadFromFile (String fileName) {try {//read from file.} catch (Exception ex) {//catching general Exception is Bad ... we'll never know whether it//was a file error or some the other error. This is are hiding an exception. In this case no one would ever know that exception happened. Return "";}}
You do not have to catch general exceptions in all methods. Whatever it is, let the program crash. This will help you find most bugs in the development cycle.
You can handle all general exceptions using the application-level (thread-level) error handler. When "General error outside" is encountered, this error handler should catch an exception, prompting the user to log the error message before the application closes or when the user chooses ignore and continue.
You don't have to use Try-catch for every method. used when a specific exception can occur. For example, when you write a file, handle the exception fileioexception.
Don't write too large a try-catch module. If necessary, write a separate Try-catch module for each task that is executed. This will help you figure out which piece of code is generating an exception and send a specific error message to the user
If your application requires it, you can write your own exception class. Custom exceptions should not be derived from the base class SystemException, but rather inherit from the. Iapplicationexception.



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.