c# – 代码合同最佳实践
|
关于代码合同以及使用它们的最佳实践,我有几个问题.假设我们有一个类,有几个属性(例如见下文):
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>())
{ }
}
关于我想要实现的目标的一些解释: (a)property1是必填字段.对象的正常使用不明确要求property2. 我有以下问题: >我是否应该为财产2的合同烦恼;因为property2不是必填字段,所以它应该有合同.在property2上签订合同是否表明它实际上是对象的正常使用所必需的; 如果问题看似简单,我表示歉意.我只是在寻找关于此事的想法,以及你们所考虑的最佳实践. 解决方法
这就是我建议的合同:
class Class1
{
// Fields
private string _property1; //Required for usage
private List<object> _property2; //Not required for usage
// Properties
public string Property1
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return this._property1;
}
set
{
Contract.Requires(value != null);
this._property1 = value;
}
}
public List<object> Property2
{
get
{
Contract.Ensures(Contract.Result<List<object>>() != null);
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>())
{
Contract.Requires(property1 != null);
}
[ContractInvariantMethod]
private void ContractInvariants()
{
Contract.Invariant(_property1 != null);
Contract.Invariant(_property2 != null);
}
}
这些属性具有公共行为合同,并且Invariants将捕获您稍后可能引入的任何错误,因为您向Class1添加了可能修改字段值并因此违反公共合同的逻辑.或者,如果字段可以只读(并且删除了setter),则不需要不变量. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
