嗨,我是 Fly,用 Ruby 寫 Chatbot 並挑戰30天分享心得
為確保不會沒靈感
每日含 Ruby 主題文章增加內容
https://github.com/leo424y/clean-code-ruby
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