命名规则
1. All words for variables, class, parameters…should have its own meaning and easy to get what it is used for.
Error: ResourceManager rm = new ResourceManager(); Correct: ResourceManager resourceManager = new ResourceManager(); Error: ResourceManager resourceManager0 = new ResourceManager(); Error: ResourceManager resourceManager1 = new ResourceManager(); Correct: ResourceManager resourceManagerForChs = new ResourceManager(); Correct: ResourceManager resourceManagerForEnu = new ResourceManager();
2. Don’t hesitate to use long enough names.
Error: FileStatus fileStatus = new FileStatus (); Correct: FileStatus fileStatusAfterSomeoneOpenTag = new FileStatus ();
3. Use PascalCasing for all public member, type, and namespace names consisting of multiple words.
private class UserInformation
4. PascalCasing for all method, classe names, enum and its members.
public void GetCountOfProducts()
5. Camel for parameter, temp variable, private property names
public class … { private int selectedFilesCount = 0; }
6. Interfaces: IsomeInterface
Coding Style:
1. Always use {} even if there is only 1 statement:
Error:
If(anything)
DoSomething();
Correct:
If(anything)
{
DoSomething();
}
2. Make the cyclomaticcomplexity of a method under 10:
- Cyclomaticcomplexity is 2 as there are 2 filters in ‘if’
If(someCondition)||(otherCondition)
{
}
- Complexity is 4. It increases 1 when there is a new ‘case’ added.
Switch someVarible { Case: value1 break; Case: value2 break; Case: value3 break; Default: return; }
- Below Complexity is 2 which equals its same ‘if…else…’ statement:
int affectedCount = userCount > maxUserCountAllowed ? userCount: maxUserCountAllowed;
- Complexity increases 1 when there is a new couple of ‘{ }’ added.
3. Do not replace if….else…with below statement which may cause confusion
int affectedCount = userCount > maxUserCountAllowed ? userCount: maxUserCountAllowed;
4. Use StringBuilder rather than ‘+’ when joining strings.
5. There should be empty line between different blocks:
if (something) { } //Empty line here if (somethingElse) { }
6. Put braces on a separate line:
Error: if (something) { DoSomething(); } Correct: if (something) { DoSomething(); }
7. The rough length of the line should less than 120 characters. The line count of a method should be kept below 150.
8. Each property, method and class should be declare its scope: public, private, internal public
9. Always log exceptions in catch block and never fail or skip silently.
Error: try { Registry.CurrentUser.OpenSubKey(subKey, true); regkey.SetValue("AcceptLanguage", acceptLang, RegistryValueKind.String); regkey.Close(); } catch () { //There is nothing in catch, bad style } Correct: try { Registry.CurrentUser.OpenSubKey(subKey, true); regkey.SetValue("AcceptLanguage", acceptLang, RegistryValueKind.String); regkey.Close(); } atch (NullReferenceException) { Logger.LogComment("Unable to set IE language"); }
10.Do not remove the target objects in ‘for’ or ‘foreach’ block:
Error: for (int i = 0; i < Files.Count; i++) { Remove(Files[i]); }
11.Avoid magic numbers or strings.
Error: Update(Users[1]); Register(“afex01c2asvr23adv”); Correct: Int IndexOfUserToUpdate = 1; Update(Users[IndexOfUserToUpdate]); string userHashId = “afex01c2asvr23adv”; Register(userHashId);
12.Pay attention to the out Index of range in ‘for’ block and Infinite Loop in while
13.Do not hard code.
Error: string filePath = @“D:\products” Correct: string filePath = ConfigurationManeger.AppSettings[“FilePath”];
14.All variables must be initialized.
int selectedFileCount = 0; FileInfo fileInfo = null;
15.The return value of methods which do not return void should be set to some variable.
Error: public void SomeMethod() { InsertIntoDB(FileArray files); } private int InsertIntoDB(FileArray files) { … return affectedCount; } Correct: public void SomeMethod() { int affectedRowCount = InsertIntoDB(FileArray files); } private int InsertIntoDB(FileArray files) { … return affectedCount; }
16.Do not use ‘ref’/’out’ meaninglessly:
Error: public void GetMessage(ref string message) { message = “This is message”; } Correct: public string GetMessage() { return “This is message”; } Remember to release memory: Person person = null; foreach(string personName in names) { person = new Person(personName); AddToDB(person); person.Dispose(); }
18.Avoid unnecessary judement.
private bool Method() private bool Method() { { if(GetFile()) return GetFile(); { } return true; => } else { return false; } }
19.Use methods in framework:
if (IsNullOrEmpty(exampleString)) //Do not use { DoSomething(); } String exampleString = String.Empty; //Do not use string = “”; If the vaule is not null, used Equals instead of ‘==’ If (exampleString.Equals(“empty”)) { DoSomething(); }
20.Try to avoid recursion if you have another way to implement due to it costs too much time.
21.Make sure to add comments to all methods and properties:
/// <summary> /// Retrieve all of the documents in the collection /// </summary> /// <param name="client">Document Client</param> /// <param name="collectionUri">The document collection URI</param> /// <returns>The documents in the collection retrieved</returns> public List<T> GetAllDocuments(DocumentClient client, string collectionUri) { return GetDocumentsByFilter(client, collectionUri, "Select * from c").Result; }
Advanced technology
Consider the extensibility and using design patterns rather than accumulation of code: Singleton, factory, Decorator, Observer…
- Keep your knowledge up to date. E.g. Use TAP instead of EAP.
- Think of scalability.
- Think of the cloud circumstance.
- High Cohesion, Low Coupling
√