iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 21
0
影片教學

懶人寫寫 BOT系列 第 21

Day 21 Clean Code Ruby

  • 分享至 

  • xImage
  •  

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

函數式地開發吧

讓你好好測試

Bad:

programmer_output = [
  {
    name: 'Uncle Bobby',
    lines_of_code: 500
  }, {
    name: 'Suzie Q',
    lines_of_code: 1500
  }, {
    name: 'Jimmy Gosling',
    lines_of_code: 150
  }, {
    name: 'Grace Hopper',
    lines_of_code: 1000
  }
]

total_output = 0

programmer_output.each do |output|
  total_output += output[:lines_of_code]
end

Good:

programmer_output = [
  {
    name: 'Uncle Bobby',
    lines_of_code: 500
  }, {
    name: 'Suzie Q',
    lines_of_code: 1500
  }, {
    name: 'Jimmy Gosling',
    lines_of_code: 150
  }, {
    name: 'Grace Hopper',
    lines_of_code: 1000
  }
]

INITIAL_VALUE = 0

total_output = programmer_output
               .reduce(INITIAL_VALUE) { |acc, output| acc + output[:lines_of_code] }
               

### 包裝判斷式

**Bad:**
```ruby
if params[:message].present? && params[:recipient].present?
  # ...
end

Good:

def send_message?(params)
  params[:message].present? && params[:recipient].present?
end

if send_message?(params)
  # ...
end

避免反判斷

Bad:

if !genres.blank?
  # ...
end

Good:

unless genres.blank?
  # ...
end

# or

if genres.present?
  # ...
end

抽象取代判斷

Bad:

class Airplane
  # ...
  def cruising_altitude
    case @type
    when '777'
      max_altitude - passenger_count
    when 'Air Force One'
      max_altitude
    when 'Cessna'
      max_altitude - fuel_expenditure
    end
  end
end

Good:

class Airplane
  # ...
end

class Boeing777 < Airplane
  # ...
  def cruising_altitude
    max_altitude - passenger_count
  end
end

class AirForceOne < Airplane
  # ...
  def cruising_altitude
    max_altitude
  end
end

class Cessna < Airplane
  # ...
  def cruising_altitude
    max_altitude - fuel_expenditure
  end
end

上一篇
Day 20 Function - Prevent Side Effect - Clean Code Ruby
下一篇
Day 22 Type-checking - Clean Code Ruby
系列文
懶人寫寫 BOT30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言