肥仔教程网

SEO 优化与 Web 开发技术学习分享平台

C++核心准则边译边学-I.1: 使接口清晰明确

I.1: Make interfaces explicit(使接口清晰明确)

Reason(原因)

Correctness. Assumptions not stated in an interface are easily overlooked and hard to test.

正确性。在接口中没有说明的假设很容易被忽视且难于测试。

Example, bad(反面示例)

Controlling the behavior of a function through a global (namespace scope) variable (a call mode) is implicit and potentially confusing. For example:

通过全局(命名空间范围)变量(调用模式)控制函数行为的方式是隐晦且不易理解的,例如:

int round(double d)
{
 return (round_up) ? ceil(d) : d; // don't: "invisible" dependency
}

It will not be obvious to a caller that the meaning of two calls of round (7.2) might give different results.

调用者不容易理解两次调用 round(7.2) 可能返回不同的结果。

Exception(例外)

Sometimes we control the details of a set of operations by an environment variable, e.g., normal vs. verbose output or debug vs. optimized. The use of a non-local control is potentially confusing, but controls only implementation details of otherwise fixed semantics.

有时我们通过环境变量控制一套操作的细节。例如,正常输出还是详细输出,也可能是调试还是优化。使用非局部控制的做法可能会难于理解,只可以应用在其他固定语义的实现细节的情况。

Example, bad(反面示例)

Reporting through non-local variables (e.g., errno) is easily ignored.

For example:

通过非局部变量报告(例如错误编码)很容易被忽略。例如:

// don't: no test of printf's return value
fprintf(connection, "logging: %d %d %d\n", x, y, s);

What if the connection goes down so that no logging output is produced? See I.???.

如果连接被关闭而导致没有日志输出怎么办?参考I.???

Alternative: Throw an exception. An exception cannot be ignored.

可选项:抛出异常。异常不会被忽略。

Alternative formulation: Avoid passing information across an interface through non-local or implicit state. Note that non-const member functions pass information to other member functions through their object's state.

另一种说法:避免会用非局部或隐含状态通过接口传递信息。注意非const成员通过对象状态函数向另外一个成员函数传递信息的情况。

Alternative formulation: An interface should be a function or a set of functions. Functions can be template functions and sets of functions can be classes or class templates.

另一种说法:接口应该是一个或一组函数。接口可以是模板函数,函数组可以是类和类模板。

Enforcement(实施建议)

  • (Simple) A function should not make control-flow decisions based on the values of variables declared at namespace scope.

(简单)函数不应该根据命名空间范围中的变量决定控制流。

  • (Simple) A function should not write to variables declared at namespace scope.

(简单)函数不应该改写定义于命名空间范围的变量。


觉得本文有帮助?请分享给更多人。

更多更新文章,欢迎关注微信公众号【面向对象思考】

面向对象设计,面向对象编程,面向对象思考!

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言