<The Art of Readable Code> 笔记二 (下)

第2章  封装信息到名字 (Packing information into names)

 

2.4  附加额外信息

1)  encode value type 

  对于某些变量,附加额外的信息可以让人更好的理解,比如,一个16进制的变量,显然 hex_id 要比  id 更为贴切

string  id;     // Example: "af84ef845cd8"
string  hex_id;

2)  encode value units

  下面的 JavaScript 代码,乍看没有任何问题,但实际上 getTime() 返回值的单位是 ms 而不是 s

var start = (new Date()).getTime(); // top of the page
...
var elapsed = (new Date()).getTime() - start; // bottom of the page
document.writeln("Load time was: " + elapsed + " seconds");

  将 _ms 作为后缀加到变量的后面,则会使代码变得更为清晰

var start_ms = (new Date()).getTime(); // top of the page
...
var elapsed_ms = (new Date()).getTime() - start_ms; // bottom of the page
document.writeln("Load time was: " + elapsed_ms / 1000 + " seconds");

   除了时间以外,还有一些别的单位如下表所示:

 Fucntion parameter  Renaming parameter to encode units
 Start (int  delay)  delay -> delay_secs
 CreateCache (int  size)  size -> size_mb
 ThrottleDownload(float  limit)  limit -> max_kbps
 Rotate (float  angle)  angle -> degrees_cw

 3)  encode other attributes

  如上述漫画所示,一些有关安全的变量命名,也常常需要一些额外的信息

 Situation  Variable name  Better name
 A password is in "plaintext" and should be encrypted before further processing  password  plaintext_passord
 A user-provided comment that needs escaping before being displayed  comment  unescaped_comment
 Byte of html have been converted to UTF-8  html  html_utf8
 Incoing data has been "url encoded"  data  data_urlenc

2.5  长名长域,短名短域

1)  短名短作用域

  变量 m 并没有封装任何信息,但是因为只在 if 作用域内有效,所以并不对妨碍代码的理解

if (debug) {
  map<string,int> m;
  LookUpNamesNumbers(&m);
  Print(m);
}

2)  善用缩写

  当变量名实在太长时,可考虑缩写,其使用原则就是:新加入的团队成员,也能够理解该缩写的意思 

  例如,evaluation 常缩写为 eval,document 可缩写为 doc,string 缩写为 str

3)  去掉无用词

  比如,ToString() 优于 ConvertToString(),ServeLoop() 也比 DoServeLoop() 简洁

2.6  使用大写或下划线

   在谷歌 C++ Style Guide 中,成员变量名字后面都带有下划线 "_";常量的命名形式为 kConstantName,以便和 #define MACRO_NAME 宏区分开来;类名一般是各个首字母大写,同样成员函数名也是如此

static const int kMaxOpenFiles = 100;
class LogReader {
public:
    void OpenFile(string local_file);
private:
    int offset_;
    DISALLOW_COPY_AND_ASSIGN(LogReader);
};
原文地址:https://www.cnblogs.com/xinxue/p/7340145.html