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: 儘量壓縮作用域


分享到:


相關文章: