一系列大多數合理的指南和最佳實踐,以編寫乾淨,可讀,易於理解和可維護的C#代碼。
var目的:更好的可讀性和清潔度
好的
var httpClient = new HttpClient ( ) ;壞的
HttpClient httpClient = new HttpClient ( ) ; 目的:更好的可讀性和清潔度
好的
var user = new User
{
Username = "admin" ,
Age = 31
} ;壞的
var user = new User ( ) ;
user . Username = "admin" ;
user . Age = 31 ; string.Format目的:更好的可讀性和語義
好的
var url = "http://localhost/api" ;
var resource = "users" ;
var path = $ " { url } / { resource } " ;壞的
var url = "http://localhost/api" ;
var resource = "users" ;
var path = string . Format ( "{0}/{1}" , url , resource ) ;目的:無需逃脫反閃爍字符
好的
var path = @"C:UsersAdministratorDocuments" ;壞的
var path = "C: \ Users \ Administrator \ Documents" ;目的:當整個地方分發字符串文字時,重構可能成為一場噩夢
好的
const string error = "user_not_found" ;
Log . Error ( error ) ;
return BadRequest ( error ) ;壞的
Log . Error ( "user_not_found" ) ;
return BadRequest ( "user_not_found" ) ; xyz節省了時間。這太荒謬了。目的:縮短變量名稱不會添加任何值,甚至使代碼更難讀取和理解
好的
// Nice
var validationResult = validator . Validate ( ) ;
// Nice
var stringBuilder = new StringBuilder ( ) ;
// Nice
const string directorySeparator = "/" ;壞的
//
var res = validator . Validate ( ) ;
//
var sbd = new StringBuilder ( ) ;
// Seriously?
const string dsep = "/" ;目的:使代碼非常易於閱讀,維護和使用
好的
// The purpose of this class can be easily inferred
public class OrderManager
{
// Using "Is" or "Has" as prefix clearly indicates that a method returns a boolean value
public bool IsFulfilled ( Order order )
{
}
public bool HasPositions ( Order order )
{
}
// Using a verb clearly indicates that a method performs some action
public void ProcessOrder ( Order order )
{
}
public void CancelOrder ( Order order )
{
}
}壞的
// Purpose of this class can not be easily inferred
public class OrderHelper
{
// Unclear
public bool Fulfilled ( Order order )
{
}
// Unclear => users would likely expect a method that retrieves the positions of the order due to the verb "Get"
public bool GetPositions ( Order order )
{
}
// Unclear
public void Order ( Order order )
{
}
// Unclear
public void StopOrder ( Order order )
{
}
}目的:使代碼不必要地更長,更難閱讀和理解
好的
// Clearly an interface
public interface IOrderManager { }
// Clearly a list of orders
private IList < Order > orders ;壞的
// Clearly an interface => no "Interface" postfix necessary
public interface IOrderManagerInterface { }
// Clearly a list of oders => no "List" postfix necessary
private IList < Order > orderList ;目的:實踐表明,隨著代碼庫的增長和發展,評論可以很容易地,快速地出現。擁有自我解釋的代碼基礎有助於更好地維護性,並減少了寫作和維持不明智的評論的必要性。 (這並不意味著寫評論已過時。)
好的
public class OrderManager
{
public void ProcessOrder ( Order order )
{
var items = order . GetItems ( ) ;
foreach ( var item in items )
{
var availability = item . GetAvailability ( ) ;
}
}
}壞的
public class OrderManager
{
public void ExecuteOrder ( Order order )
{
// Get all available items from the order
var data = order . GetData ( ) ;
foreach ( var x in data )
{
// Determine the availability of the item
var available = item . CheckAvailability ( ) ;
}
}
}目的:與.NET框架一致,易於閱讀
好的
public class JsonParser { }壞的
public class JSONParser { }目的: enum總是單獨解決。例如, EmploymentType.FullTime比EmploymentTypes.FullTime要乾淨得多。此外,類始終代表對象的一個實例,例如單個User 。例外:位字段枚舉
好的
public enum EmploymentType
{
FullTime ,
PartTime
}
public class User
{
}壞的
public enum EmploymentTypes
{
FullTime ,
PartTime
}
public class Users
{
} 目的:句法糖 (ツ) /
好的
public class User
{
public string Username { get ; }
public int Age { get ; }
public string DisplayName => $ " { Username } ( { Age } )" ;
public User ( string username , int age )
{
Username = username ;
Age = age ;
}
}壞的
public class User
{
public string Username { get ; }
public int Age { get ; }
public string DisplayName
{
get
{
return $ " { Username } ( { Age } )" ;
}
}
public User ( string username , int age )
{
Username = username ;
Age = age ;
}
} 目的:更好地意識到出了問題。在記錄和錯誤分析過程中允許更精確。
好的
try
{
System . IO . File . Open ( path ) ;
}
catch ( FileNotFoundException ex )
{
// Specific
}
catch ( IOException ex )
{
// Specific
}
catch ( Exception ex )
{
// Default
}壞的
try
{
System . IO . File . Open ( path ) ;
}
catch ( Exception ex )
{
// SOMETHING went wrong
}Exception目的:非常糟糕的練習。 Exception S僅由.NET框架拋出。
好的
public void ProcessOrder ( Order order )
{
if ( order == null )
{
throw new ArgumentNullException ( nameof ( order ) ) ;
}
}壞的
public void ProcessOrder ( Order order )
{
if ( order == null )
{
throw new Exception ( "Order is null." ) ;
}
} 目的:更好的可讀性
好的
private string _username ;壞的
private string mUsername__ ;
// OR
private string username ;
// OR
private string username_ ; 目的:更好的可讀性,節省空間
好的
public class JsonParser
{
private readonly string _json ;
public JsonParser ( string json )
{
_json = json ;
}
}壞的
public class JsonParser
{
private readonly string _json ;
public JsonParser ( string json )
{
_json = json ;
}
} 目的:防止財產從其他地方意外更改,更好地預測應用程序行為
好的
public class JsonParser
{
public string Json { get ; }
public JsonParser ( string json )
{
Json = json ;
}
}壞的
public class JsonParser
{
public string Json { get ; set ; }
public JsonParser ( string json )
{
Json = json ;
}
}目的:防止收集從其他地方更改,更好地預測應用程序行為
好的
public class KeywordProvider
{
public IReadOnlyCollection < string > Keywords { get ; }
public KeywordProvider ( )
{
Keywords = new ReadOnlyCollection < string > ( new List < string >
{
"public" ,
"string"
} ) ;
}
}壞的
public class KeywordProvider
{
public IList < string > Keywords { get ; }
public KeywordProvider ( )
{
Keywords = new List < string >
{
"public" ,
"string"
} ;
}
} using塊目的:當using塊完成時,資源將自動處置
好的
using ( var connection = new SqlConnection ( connectionString ) )
{
}壞的
try
{
var connection = new SqlConnection ( connectionString ) ;
}
finally
{
connection . Close ( ) ;
connection . Dispose ( ) ;
} 目的:更好的可讀性,在條件內需要另一行時更容易維護
好的
if ( user . IsElevated )
{
// Do something
}壞的
if ( user . IsElevated )
// Do something目的:以便您知道消息的哪一部分包含變量。
好的
var filePath = @"C:tmpmy-file.txt" ;
try
{
var file = File . Open ( filePath ) ;
}
catch ( Exception ex )
{
// GOOD: Add [ ] to the variable
Log . Error ( $ "Could not open file [ { filePath } ]." , ex ) ;
}壞的
var filePath = @"C:tmpmy-file.txt" ;
try
{
var file = File . Open ( filePath ) ;
}
catch ( Exception ex )
{
Log . Error ( $ "Could not open file { filePath } ." , ex ) ;
}目的:以便在某些情況下可以過濾例外(例如,在用戶界面中,由於用戶對整個堆棧跟踪無用)。
好的
try
{
var file = File . Open ( @"C:tmpmy-file.txt" ) ;
}
catch ( Exception ex )
{
// Use appropriate signature of your logger to include the exception as separate parameter
Log . Error ( "Could not open file." , ex ) ;
}壞的
try
{
var file = File . Open ( @"C:tmpmy-file.txt" ) ;
}
catch ( Exception ex )
{
// Strictly AVOID this. The exception is added directly to the log message, which makes it impossible to filter the exception
Log . Error ( $ "Could not open file: { ex } " ) ;
}