2012-09-12 32 views
1

C#中的類是否有確定的推薦佈局?類的佈局

這裏是與佈局的問題的例子...

public class DinnerParty { 

     //>>>>should the const fields that are initiallised with a value be at the top? 
    private const int CostOfFoodPerPerson = 25; 

     //>>>>should the constructor always be placed near the top of the class? 
    public DinnerParty(int numberOfPeople, bool Health, bool fancyDecorations) { 
     NumberOfPeople = numberOfPeople; 
     this.fancyDecorations = fancyDecorations; 
     Health = healthyOption; 
     CalculateCostOfDecorations(fancyDecorations); 
    } 

     //>>>>backing private fields should always precede properties that use them? 
    private int numberOfPeople; 
    public int NumberOfPeople { 
     get { 
      return numberOfPeople; 
     } 
     set { 
      CalculateCostOfDecorations(fancyDecorations); 
      numberOfPeople = value; 
     } 
    } 

     //>>>>where do these fields go? 
    private bool fancyDecorations; 
    public decimal costOfBeveragePerPerson; 

    private bool healthyOption; 
    public bool HealthyOption{ 
     set { 
      value = healthyOption; 
      if (healthyOption) { 
       costOfBeveragePerPerson = 5.0M; 
      } else { 
       costOfBeveragePerPerson = 20.0M; 
      } 
     } 
    } 

    //>>>>should methods be placed after the constructor and all properties? 
    public decimal costOfDecorations = 0; 
    void CalculateCostOfDecorations(bool fancy) { 
     if (fancy) { 
      costOfDecorations = (numberOfPeople * 15.0M) + 50.0M; 
     } else { 
      costOfDecorations = (numberOfPeople * 7.50M) + 30.0M; 
     } 
    } 

    public decimal CalculateCost(bool xfancy, bool xhealthyOption) { 
     decimal totalCost = (numberOfPeople * (CostOfFoodPerPerson + costOfBeveragePerPerson)) + costOfDecorations; 
     if (xhealthyOption) { 
      return totalCost * 0.95M; 
     } else { 
      return totalCost; 
     } 
    } 
} 
+0

看起來像這樣可能會關閉;我懷疑是不夠具體 - 任何人有任何提示編輯的問題,使其更容易接受? (我覺得這個問題可能的答案是有用的) – whytheq

+0

它屬於SO代碼審查或程序員沒有真正涵蓋的半代碼審查領域。我認爲這不是一個好問題,但它可能會成爲一個OK-IS社區維基。 –

+0

@AdamHouldsworth如何將其切換到社區wiki? – whytheq

回答

1

了StyleCop具有以下規則:

  • 在類,結構或接口,元件必須定位在下面的順序:

    • 常量字段
    • FIEL DS
    • 構造
    • 終結(析構函數)
    • 代表
    • 活動
    • 枚舉
    • 接口
    • 屬性
    • 索引器
    • 方法
    • 的Structs
  • 同類型必須由訪問級別定位在下列順序的元素:

    • 公共
    • 內部
    • 保護內部
    • 保護
    • 私人
  • 所有靜態元素必須放置在相同類型的所有實例元素之上。

查看the documentation瞭解詳情。

+0

當然,這些規則是可選的;-) –

+0

@AdamHouldsworth:是的,當然。但是它們是.NET世界中的一個被接受的標準。 –

+0

@AdamHouldsworth:將ReSharpers Clean Code工具與StyleCop插件一起使用,並使用匹配的配置,您可以在幾分鐘內更改完整的代碼庫以遵守規則。 –

0

就個人而言,我做...

  • 變量聲明
  • 方法
  • 屬性 ......的順序。

其他人有自己的喜好。我能想到的唯一硬性規則是是一致的 - 無論您的偏好如何,如果您清楚&可預測,它使得下一個人更容易拿起。

1

我朝傾向於:

  • 活動
  • 領域(包括常量)
  • 屬性(包括索引器和自動屬性)
  • 構造
  • 公共/保護/內部/私有方法。
  • 嵌套類型

這麼說,我儘量尊重文件的順序,因爲它主張,因爲不必要移動的東西圍繞導致合併痛苦

我不確定是否有明確的寫作課程內容的方式;即使有,我會拿一小撮鹽,在一天結束時,這也只是某人的意見。保持一致,只是儘量保持代碼整潔(我個人討厭它時,代碼文件亂七八糟隨機空白按輸入太多次)。

幫助合併的另一個重要因素仍然是可信的,就是在代碼格式設置上有一致的設置(內聯與新行括號,圍繞單行if語句的括號等)。