C++核心准则ES.5: 尽量压缩作用域

C++核心准则ES.5: 尽量压缩作用域

ES.5: Keep scopes small

ES.5: 尽量压缩作用域

Reason(原因)

Readability. Minimize resource retention. Avoid accidental misuse of value.

可读性。最小化资源的保持时间。避免变量的误用。

Alternative formulation: Don't declare a name in an unnecessarily large scope.

换个说法:不要没有必要扩大名称的作用域。

Example(示例)

<code>void use()
{
int i; // bad: i is needlessly accessible after loop
for (i = 0; i < 20; ++i) { /* ... */ }
// no intended use of i here
for (int i = 0; i < 20; ++i) { /* ... */ } // good: i is local to for-loop

if (auto pc = dynamic_cast<circle>(ps)) { // good: pc is local to if-statement
// ... deal with Circle ...
}
else {
// ... handle error ...
}
}/<circle>/<code>

Example, bad(反面示例)

<code>void use(const string& name)
{
string fn = name + ".txt";

ifstream is {fn};
Record r;
is >> r;
// ... 200 lines of code without intended use of fn or is ...
}/<code>

This function is by most measure too long anyway, but the point is that the resources used by fn and the file handle held by is are retained for much longer than needed and that unanticipated use of is and fn could happen later in the function. In this case, it might be a good idea to factor out the read:

这个函数用任何标准衡量都太长了,但是要点在于fn使用的资源和is管理的文件被维持的时间远远超过需要,有可能在函数接下来的部分is和fn会被意外使用。这种情况下,分解出一个read函数可能是一个好主意。

<code>Record load_record(const string& name)
{
string fn = name + ".txt";
ifstream is {fn};
Record r;
is >> r;
return r;
}

void use(const string& name)
{
Record r = load_record(name);
// ... 200 lines of code ...
}/<code>

Enforcement(实施建议)

  • Flag loop variable declared outside a loop and not used after the loop
  • 标记在循环外定义循环变量并且循环之后不再使用的情况。
  • Flag when expensive resources, such as file handles and locks are not used for N-lines (for some suitable N)
  • 标记高价值资源(例如文件句柄和锁)在N行(适当值)之内没有使用的情况。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es5-keep-scopes-small




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

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

C++核心准则ES.5: 尽量压缩作用域


分享到:


相關文章: