花括弧需獨立一行,而不象if, for 等可以跟括號在同一行。
好:
|
不好:
|
在每個運算符和括號的前後都空一格。
好:
|
不好:
if(showResult==true) { for(int i= 0;i<10;i++) { // } } |
良好的編程習慣
遵從以下良好的習慣以寫出好程序
|
避免使用大文件。如果一個文件裏的代碼超過300~400行,必須考慮將代碼分開到不同類中。
避免寫太長的方法。一個典型的方法代碼在1~25行之間。如果一個方法發代碼超過25行,應該考慮將其分解爲不同的方法。
方法名需能看出它作什麼。別使用會引起誤解的名字。如果名字一目瞭然,就無需用文檔來解釋方法的功能了。
好:
|
不好:
|
一個方法只完成一個任務。不要把多個任務組合到一個方法中,即使那些任務非常小。
好:
// 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. // ... } |
不好:
// 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. // ... } |
使用C# 或 VB.NET的特有類型,而不是System命名空間中定義的別名類型。
好:
|
不好:
|
別在程序中使用固定數值,用常量代替。
別用字符串常數。用資源文件。
避免使用很多成員變量。聲明局部變量,並傳遞給方法。不要在方法間共享成員變量。如果在幾個方法間共享一個成員變量,那就很難知道是哪個方法在什麼時候修改了它的值。
必要時使用enum 。別用數字或字符串來指示離散值。
好:
|
不好:
|
別把成員變量聲明爲 public 或 protected。都聲明爲 private 而使用 public/protected 的Properties。
不在代碼中使用具體的路徑和驅動器名。 使用相對路徑,並使路徑可編程。