近期參加公司內部的 C# 程式碼規範培訓,其中兩項規定引發了我的強烈質疑與思考。這不僅關乎個人習慣,更觸及團隊協作效率與程式碼可讀性的核心議題。
公司規定:私有欄位採用駝峰命名法,不加前綴,使用時必須加 this. 前綴。
我的慣用做法:加底線前綴(_fieldName)。
public void Test()
{
_age = DateTime.Now.Year - _birth.Year;
if (_birth > new DateTime(2000, 1, 1))
{
_name += " new century";
}
}
public void Test2()
{
this.age = DateTime.Now.Year - this.birth.Year;
if (this.birth > new DateTime(2000, 1, 1))
{
this.name += " new century";
}
}
乍看之下差異不大,但當方法包含屬性、方法、事件存取時,this. 的噪音效應顯現:
// 無 this. 版本
public void Test()
{
Prop1++;
_age = DateTime.Now.Year - _birth.Year;
Method1();
if (_birth > new DateTime(2000, 1, 1))
{
Prop2 += " abcd";
_name += " new century";
}
Event1 += () => { };
}
// 強制 this. 版本
public void Test2()
{
this.Prop1++;
this.age = DateTime.Now.Year - this.birth.Year;
this.Method1();
if (this.birth > new DateTime(2000, 1, 1))
{
this.Prop2 += " abcd";
this.name += " new century";
}
this.Event1 += () => { };
}
m_ 前綴同樣優秀,且 Visual Studio 產生屬性時會自動移除前綴並大寫首字母,極為貼心。
規定:必須使用 Int32 替代 int、Int64 替代 long。
培訓理由(參考《CLR via C#》):避免開發者誤以為 int 在 32/64 位元機器上表現不同;long 在其他語言不一定是 64 位元。
long 卻要用 Int64 接收,認知負擔重int 三鍵搞定,Int32 五鍵且需大寫;Int64 更需找鍵盤上排數字鍵,極度不適我贊同統一規範的必要性,尤其在人員流動頻繁的團隊。但規範應基於廣泛共識與工具鏈友善度制定,而非個人偏好強加。好的規範應該讓開發者「舒舒服服寫代碼,同時完成義務」。
建議決策者廣泛徵詢一線開發者意見,以實務經驗為依歸,而非單純引用權威書籍條文。
原文連結:https://www.cnblogs.com/Tyr-Tian/archive/2011/04/28/2032233.html