變數用有意義且可發音的字
Bad:
yyyymmdstr = Time.now.strftime(‘%Y/%m/%d’)
Good:
current_date = Time.now.strftime(‘%Y/%m/%d’)
同類型的變數用同一個字詞
Pick one word for the concept and stick to it.
Bad:
user_info
user_data
user_record
starts_at
start_at
start_time
Good:
user
starts_at
使用常數且易於搜尋
你讀程式的時間比寫的時間多,讓你的變數能被搜尋且好懂
Bad:
# What the heck is 86400 for?
status = Timeout::timeout(86_400) do
# …
end
Good:
# Declare them as capitalized globals.
SECONDS_IN_A_DAY = 86_400
status = Timeout::timeout(SECONDS_IN_A_DAY) do
# …
end
解釋變數
Bad:
address = ‘One Infinite Loop, Cupertino 95014’
city_zip_code_regex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/
save_city_zip_code(city_zip_code_regex.match(address)[1], city_zip_code_regex.match(address)[2])
Good:
address = ‘One Infinite Loop, Cupertino 95014’
city_zip_code_regex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/
_, city, zip_code = city_zip_code_regex.match(address).to_a
save_city_zip_code(city, zip_code)
明確不靠意會
Bad:
locations = [‘Austin’, ‘New York’, ‘San Francisco’]
locations.each do |l|
do_stuff
do_some_other_stuff
# …
# …
# …
# Wait, what is `l` for again?
dispatch(l)
end
別重工
Bad:
car = {
car_make: ‘Honda’,
car_model: ‘Accord’,
car_color: ‘Blue’
}
def paint_car(car)
car[:car_color] = ‘Red’
end
給定預設值
false 或 nil 則不會被轉成預設
Bad:
def create_micro_brewery(name)
brewery_name = name || ‘Hipster Brew Co.’
# …
end
Good:
def create_micro_brewery(brewery_name = ‘Hipster Brew Co.’)
# …
end