笔记二 (下)

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

 

2.4  附加额外信息

1)  encode value type 

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

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

2)  encode value units

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

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");

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

 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 做用域内有效,因此并不对妨碍代码的理解oop

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

2)  善用缩写

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

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

3)  去掉无用词

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

2.6  使用大写或下划线

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

static const int kMaxOpenFiles = 100;
class LogReader {
public:
    void OpenFile(string local_file);
private:
    int offset_;
    DISALLOW_COPY_AND_ASSIGN(LogReader);
};
相关文章
相关标签/搜索