iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 18
0
影片教學

懶人寫寫 BOT系列 第 18

Day 18 Variables - Clean Code Ruby

  • 分享至 

  • xImage
  •  

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

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

上一篇
Day 17 用 Line Notify 做一個元氣彈書籤
下一篇
Day 19 - Clean Code Ruby
系列文
懶人寫寫 BOT30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言