I.5: State preconditions (if any)如果存在前提,一定要说明
Reason(原因)
Arguments have meaning that may constrain their proper use in the callee.
参数的含义可能会限制它在被调用方的使用。
Example(示例)
Consider:考虑:
double sqrt(double x);
Here x
must be nonnegative. The type system cannot (easily and naturally) express that, so we must use other means. For example:
这里x必须是非负值。类型系统无法(简单且自然地)表达这件事,因此我们必须使用其他方式。例如
double sqrt(double x); // x must be nonnegative
Some preconditions can be expressed as assertions. For example:
有些前提条件可以用断言表达。例如:
double sqrt(double x) { Expects(x >= 0); /* ... */ }
Ideally, that Expects(x >= 0)
should be part of the interface of sqrt()
but that's not easily done. For now, we place it in the definition (function body).
理想情况下,这个Expects(x >=0)应该成为sqrt接口的一部分,但是这不容易实现。到目前为止,我们将它放到定义(函数体)中。
References: Expects()
is described in GSL.
参考:Expects()在GSL中有描述。
Note(注意)
Prefer a formal specification of requirements, such as Expects(p);
. If that is infeasible, use English text in comments, such as
像Expects(p)那样正式定义需求是比较好的选择。如果无法实现,可以使用英语注释,例如
// the sequence [p:q) is ordered using <.
Note(注意)
Most member functions have as a precondition that some class invariant holds. That invariant is established by a constructor and must be reestablished upon exit by every member function called from outside the class. We don't need to mention it for each member function.
很多成员函数具有类不变量包含的前提条件。不变量由构造函数建立并且必须在成员函数从类外被调用并退出时重新建立。我们不需要每个函数都提到它。
译者注:
1.类不变量是可以用于定义对象是否处于有效状态的一组条件。
2.类内调用时(私有成员函数),有时会破坏类不变量。
Enforcement(实施建议)
(Not enforceable)无法强制执行
See also: The rules for passing pointers. ???
参考:传递指针规则。???
阅读更多更新文章,请关注微信公众号【面向对象思考】