命名

命名

程序设计的真正难题是替事物命名及使缓存失效。

——Phil Karlton

  • 标识符使用英文命名。
    [link]
## 差 - 标识符使用非 ASCII 字符
заплата = 1_000

## 差 - 标识符使用拉丁文写法的保加利亚单词
zaplata = 1_000

## 好
salary = 1_000
  • 符号、方法、变量使用蛇底式小写(snake_case)。
    [link]
## 差
:'some symbol'
:SomeSymbol
:someSymbol

someVar = 5
var_10 = 10

def someMethod
  ...
end

def SomeMethod
 ...
end

## 好
:some_symbol

some_var = 5
var10 = 10

def some_method
  ...
end
  • 给符号、方法、变量命名时,避免分隔字母与数字。
    [link]
## 差
:some_sym_1

some_var_1 = 1

def some_method_1
  # 做一些事情
end

## 好
:some_sym1

some_var1 = 1

def some_method1
  # 做一些事情
end
  • 类与模块使用驼峰式大小写(CamelCase)。(HTTP、RFC、XML 等首字母缩写应该仍旧保持大写形式)
    [link]
## 差
class Someclass
  ...
end

class Some_Class
  ...
end

class SomeXml
  ...
end

class XmlSomething
  ...
end

## 好
class SomeClass
  ...
end

class SomeXML
  ...
end

class XMLSomething
  ...
end
  • 文件名使用蛇底式小写,如 hello_world.rb。
    [link]

  • 目录名使用蛇底式小写,如 lib/hello_world/hello_world.rb。
    [link]

  • 尽量使一个源文件中只有一个类或模块。文件名就是类名或模块名,但使用蛇底式小写而不是驼峰式大小写。
    [link]

  • 其他常量使用尖叫蛇底式大写(SCREAMING_SNAKE_CASE)。
    [link]

## 差
SomeConst = 5

## 好
SOME_CONST = 5
  • 谓词方法(返回布尔值的方法)的名字应当以问号结尾。(比如 Array#empty?)。不返回布尔值的方法不应以问号结尾。
    [link]

  • 谓词方法的名字应当避免使用 is、does、can 等助动词作为前缀。这些助动词在实际场景中显得冗余,且与标准库的命名习惯(比如 empty?、include?)很不一致。
    [link]

## 差
class Person
  def is_tall?
    true
  end

  def can_play_basketball?
    false
  end

  def does_like_candy?
    true
  end
end

## 好
class Person
  def tall?
    true
  end

  def basketball_player?
    false
  end

  def likes_candy?
    true
  end
end
  • 具有潜在危险性 的方法,当其存在对应安全版本的方法时,其名字应当以惊叹号结尾。(比如修改 self 或参数值的方法、相对 exit 方法不会在退出时运行 finalizers 执行清理工作的 exit! 方法等)
    [link]
## 差 - 没有对应安全版本的方法
class Person
  def update!
  end
end

## 好
class Person
  def update
  end
end

## 好
class Person
  def update!
  end

  def update
  end
end
  • 尽量根据危险方法来定义对应安全版本的方法。
    [link]
class Array
  def flatten_once!
    res = []

    each do |e|
      [*e].each { |f| res << f }
    end

    replace(res)
  end

  def flatten_once
    dup.flatten_once!
  end
end
  • 当定义二元操作符时,将参数命名为 other(<< 与 [] 例外,因为其语义与此不同)。
    [link]
def +(other)
  # 省略主体
end