iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 29
0
影片教學

懶人寫寫 BOT系列 第 29

Day 29 Formatting - Clean Code Ruby

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

Formatting

推薦RuboCop

大小寫統一

Bad:

DAYS_IN_WEEK = 7
daysInMonth = 30

songs = ['Back In Black', 'Stairway to Heaven', 'Hey Jude']
Artists = ['ACDC', 'Led Zeppelin', 'The Beatles']

def eraseDatabase; end

def restore_database; end

class ANIMAL; end
class Alpaca; end

Good:

DAYS_IN_WEEK = 7
DAYS_IN_MONTH = 30

SONGS = ['Back In Black', 'Stairway to Heaven', 'Hey Jude'].freeze
ARTISTS = ['ACDC', 'Led Zeppelin', 'The Beatles'].freeze

def erase_database; end

def restore_database; end

class Animal; end
class Alpaca; end

按照關聯順序排函式

Bad:

class PerformanceReview
  def initialize(employee)
    @employee = employee
  end

  def lookup_peers
    db.lookup(@employee, 'peers')
  end

  def lookup_manager
    db.lookup(@employee, 'manager')
  end

  def peer_reviews
    peers = lookup_peers
    # ...
  end

  def perf_review
    peer_reviews
    manager_review
    self_review
  end

  def manager_review
    manager = lookup_manager
    # ...
  end

  def self_review
    # ...
  end
end

review = PerformanceReview.new(employee)
review.perf_review

Good:

class PerformanceReview
  def initialize(employee)
    @employee = employee
  end

  def perf_review
    peer_reviews
    manager_review
    self_review
  end

  def peer_reviews
    peers = lookup_peers
    # ...
  end

  def lookup_peers
    db.lookup(@employee, 'peers')
  end

  def manager_review
    manager = lookup_manager
    # ...
  end

  def lookup_manager
    db.lookup(@employee, 'manager')
  end

  def self_review
    # ...
  end
end

review = PerformanceReview.new(employee)
review.perf_review

上一篇
Day 28 Error Handling - Clean Code Ruby
下一篇
Day 30 Comments - Clean Code Ruby
系列文
懶人寫寫 BOT30

尚未有邦友留言

立即登入留言