我打算使用新的.NET 4 Code Contracts功能进行未来的开发.这让我想知道我们是否必须Contract.Requires(...)在一系列方法中冗余地指定等效语句.
我认为一个代码示例胜过千言万语:
public bool CrushGodzilla(string weapon, int velocity)
{
Contract.Requires(weapon != null);
// long code
return false;
}
public bool CrushGodzilla(string weapon)
{
Contract.Requires(weapon != null); // specify contract requirement here
// as well???
return this.CrushGodzilla(weapon, int.MaxValue);
}
Run Code Online (Sandbox Code Playgroud)
对于运行时检查它并不重要,因为我们最终总是会遇到需求检查,如果失败我们会收到错误.
但是,当我们再次在第二次超载中没有指定合同要求时,它被认为是不好的做法吗?
此外,还将具有编译时检查的功能,并且还可能设计代码合同的时间检查.在Visual Studio 2010中,它似乎尚不适用于C#,但我认为有一些类似Spec#的语言已经可以使用.当我们编写代码来调用这样的方法时,这些引擎可能会给我们提示,而我们的参数目前可以或将会是null.
所以我想知道这些引擎是否总是会分析一个调用堆栈,直到找到一个目前不满意的合同方法?
此外,在这里我了解到的区别Contract.Requires(...)和Contract.Assume(...).我想在这个问题的背景下还要考虑差异呢?
我想知道是否有办法限制建筑价值.这是我的代码:
class Student : Human
{
private double Grade;
public Student(string FirstName, string LastName, double Grade)
: base(FirstName, LastName)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.Grade = Grade;
}
}
Run Code Online (Sandbox Code Playgroud)
当我创建一个新学生时,我希望将等级限制在> = 2.00和<= 6.00之间,如编译错误或运行时异常.有办法吗?(不要担心其他字段FirstName和LastName)
据我所知,在DbC方法中,前置条件和后置条件附加到函数中.
我想知道的是,这是否也适用于成员函数.
例如,假设我在每个公共函数末尾的开头使用不变量,成员函数将如下所示:
编辑:(清理我的例子)
void Charcoal::LightOnFire() {
invariant();
in_LightOnFire();
StartBurning();
m_Status = STATUS_BURNING;
m_Color = 0xCCCCCC;
return; // last return in body
out_LightOnFire();
invariant();
}
inline void Charcoal::in_LightOnFire() {
#ifndef _RELEASE_
assert (m_Status == STATUS_UNLIT);
assert (m_OnTheGrill == true);
assert (m_DousedInLighterFluid == true);
#endif
}
inline void Charcoal::out_LightOnFire() {
#ifndef _RELEASE_
assert(m_Status == STATUS_BURNING);
assert(m_Color == 0xCCCCCC);
#endif
}
// class invariant
inline void Charcoal::invariant() {
assert(m_Status == STATUS_UNLIT || m_Status == STATUS_BURNING || m_Status == STATUS_ASHY);
assert(m_Color == 0x000000 …Run Code Online (Sandbox Code Playgroud) design-by-contract invariants member-functions preconditions