最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

Day 18 Variables – Clean Code Ruby

XAMPP下载 admin 623浏览 0评论
 Variables
變數用有意義且可發音的字
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

转载请注明:XAMPP中文组官网 » Day 18 Variables – Clean Code Ruby

您必须 登录 才能发表评论!