C++核心準(zhǔn)則ES.2: 適當(dāng)?shù)某橄蠛糜谥苯邮褂谜Z言功能

ES.2: Prefer suitable abstractions to direct use of language features
ES.2: 適當(dāng)?shù)某橄蠛糜谥苯邮褂谜Z言功能
Reason(原因)
A "suitable abstraction" (e.g., library or class) is closer to the application concepts than the bare language, leads to shorter and clearer code, and is likely to be better tested.
“適當(dāng)?shù)某橄蟆保ɡ鐜旎蝾悾┍戎苯邮褂谜Z言功能更接近應(yīng)用概念,這會帶來更短、更清晰的代碼,很有可能被更好地測試。
Example(示例)
vector read1(istream& is) // good
{
vector res;
for (string s; is >> s;)
res.push_back(s);
return res;
}
The more traditional and lower-level near-equivalent is longer, messier, harder to get right, and most likely slower:
更加傳統(tǒng)的、低層次的差不多等價的代碼會更長,更亂,更難保證正確性,而且很有可能更慢。
char** read2(istream& is, int maxelem, int maxstring, int* nread) // bad: verbose and incomplete
{
auto res = new char*[maxelem];
int elemcount = 0;
while (is && elemcount < maxelem) {
auto s = new char[maxstring];
is.read(s, maxstring);
res[elemcount++] = s;
}
nread = &elemcount;
return res;
}
Once the checking for overflow and error handling has been added that code gets quite messy, and there is the problem remembering to?delete?the returned pointer and the C-style strings that array contains.
一旦增加了溢出檢查,錯誤處理,代碼會變得很亂,而且還存在需要記住銷毀返回的指針和數(shù)組包含的C風(fēng)格字符串的問題。
Enforcement(實施建議)
Not easy. ??? Look for messy loops, nested loops, long functions, absence of function calls, lack of use of non-built-in types. Cyclomatic complexity?
不容易,不容易。尋找混亂的循環(huán)、嵌套循環(huán)、長函數(shù)、函數(shù)調(diào)用缺失、很少被使用的內(nèi)置類型?還是確認(rèn)圈復(fù)雜度?
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es2-prefer-suitable-abstractions-to-direct-use-of-language-features
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
