C++核心准则ES.7: 通用和局部的名称应该简短,特殊和非局部的名称...
共 449字,需浏览 1分钟
·
2020-04-18 23:20
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;在这个通用函数中,关于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:
长函数的参数名属于事实上的非局部变量,应该具有明确的含义:
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.
我们推荐保持函数简短,但是该规则不会适用于所有情况,名称也应该反映这种变化。
Enforcement(实施建议)
Check length of local and non-local names. Also take function length into account.
检查局部和非局部变量的长度。注意同时考虑函数的长度。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es7-keep-common-and-local-names-short-and-keep-uncommon-and-non-local-names-longer
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!