C++核心準則ES.7: 通用和局部的名稱應該簡短,特殊和非局部的名稱...

ES.7: Keep common and local names short, and keep uncommon and non-local names longer
ES.7: 通用和局部的名稱應該簡短,特殊和非局部的名稱應該較長。
Reason(原因)
Readability. Lowering the chance of clashes between unrelated non-local names.
可讀性。避免無關的非局部名稱之間的沖突。
Example(示例)
Conventional short, local names increase readability:
遵循慣例的,簡短的局部變量可以增加可讀性。
template // good
void print(ostream& os, const vector& v)
{
for (gsl::index i = 0; i < v.size(); ++i)
os << v[i] << '\n';
}
An index is conventionally called?i?and there is no hint about the meaning of the vector in this generic function, so?v?is as good name as any. Compare
索引習慣上命名為i;在這個通用函數(shù)中,關于vector的含義沒有任何參考信息,因此v也是一個好名字。
template // bad: verbose, hard to read
void print(ostream& target_stream, const vector& current_vector)
{
for (gsl::index current_element_index = 0;
current_element_index < current_vector.size();
++current_element_index
)
target_stream << current_vector[current_element_index] << '\n';
}
Yes, it is a caricature, but we have seen worse.
是的,這段代碼有點夸張,但是我們確實看過更差的。
Example(示例)
Unconventional and short non-local names obscure code:
特殊且很短的非局部名稱會擾亂代碼:
void use1(const string& s)
{
// ...
tt(s); // bad: what is tt()?
// ...
}
Better, give non-local entities readable names:
稍好一點的做法是,為非局部實體提供可讀的名稱:
void use1(const string& s)
{
// ...
trim_tail(s); // better
// ...
}
Here, there is a chance that the reader knows what?trim_tail?means and that the reader can remember it after looking it up.
存在這樣的可能性:讀者能夠理解trim_tail的含義并且可以在查閱代碼之后能夠記住它。
Example, bad(反面示例)
Argument names of large functions are de facto non-local and should be meaningful:
長函數(shù)的參數(shù)名屬于事實上的非局部變量,應該具有明確的含義:
void complicated_algorithm(vector& vr, const vector& vi, map& out)
// read from events in vr (marking used Records) for the indices in
// vi placing (name, index) pairs into out
{
// ... 500 lines of code using vr, vi, and out ...
}
We recommend keeping functions short, but that rule isn't universally adhered to and naming should reflect that.
我們推薦保持函數(shù)簡短,但是該規(guī)則不會適用于所有情況,名稱也應該反映這種變化。
Enforcement(實施建議)
Check length of local and non-local names. Also take function length into account.
檢查局部和非局部變量的長度。注意同時考慮函數(shù)的長度。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es7-keep-common-and-local-names-short-and-keep-uncommon-and-non-local-names-longer
覺得本文有幫助?請分享給更多人。
關注微信公眾號【面向?qū)ο笏伎肌枯p松學習每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
