我有幾個關於代碼合同的問題及其使用的最佳實踐。比方說,我們有一個類,有幾個屬性(見下文的例子):代碼合同最佳實踐
class Class1
{
// Fields
private string _property1; //Required for usage
private List<object> _property2; //Not required for usage
// Properties
public string Property1
{
get
{
return this._property1;
}
set
{
Contract.Requires(value != null);
this._property1 = value;
}
}
public List<object> Property2
{
get
{
return this._property2;
}
set
{
Contract.Requires(value != null);
this._property2 = value;
}
}
public Class1(string property1, List<object> property2)
{
Contract.Requires(property1 != null);
Contract.Requires(property2 != null);
this.Property1 = property1;
this.Property2 = property2;
}
public Class1(string property1)
: this(property1, new List<object>())
{ }
}
一些解釋什麼,我想實現:
(一)property1是必填字段。對於正常使用對象而言,property2並不是明確需要的。
我有以下問題:
應我甚至與合同property2麻煩;因爲property2不是必填字段,所以它應該有合同。在物業上籤訂合同2是否表明它實際上是正常使用物品所必需的;
儘管property2沒有明確要求,但沒有可能的原因爲null,因此在setter中定義了契約。不會在property2上定義合同會減少調用代碼中的空檢查嗎?這應該可以減少錯誤並提高代碼的可維護性 - 這個假設是否正確?
如果它是正確的,我如何確保調用代碼property2永遠不會爲空?我使用Contract.Invariant(property2!= null);或者在構造函數中使用Contract.Ensures(property2!= null),或者在Init()中使用Contract.Ensures(property2!= null),或者使用setter中的Contract.Ensures(property!= null) (即如果使用Contract.Ensures(property2!= null),它放在哪裏)?
如果問題看起來很簡單,我很抱歉。我只是在尋找關於這個問題的想法,以及你們認爲最好的做法。
我與財產2合同爲您列出的理由達成一致。 –