一系列大多数合理的指南和最佳实践,以编写干净,可读,易于理解和可维护的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 } " ) ;
}