iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 24
0
影片教學

懶人寫寫 BOT系列 第 24

Day 24 Objects and Data Structures - Clean Code Ruby

  • 分享至 

  • xImage
  •  

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

使用 Getter, Setter

Bad:

def make_bank_account
  # ...

  {
    balance: 0
    # ...
  }
end

account = make_bank_account
account[:balance] = 100
account[:balance] # => 100

Good:

class BankAccount
  def initialize
    # this one is private
    @balance = 0
  end

  # a "getter" via a public instance method
  def balance
    # do some logging
    @balance
  end

  # a "setter" via a public instance method
  def balance=(amount)
    # do some logging
    # do some validation
    @balance = amount
  end
end

account = BankAccount.new
account.balance = 100
account.balance # => 100

Good:

class Toy
  attr_accessor :price
end

toy = Toy.new
toy.price = 50
toy.price # => 50

上一篇
Day 23 Remove useless code - Clean Code Ruby
下一篇
Day 25 Classes - Clean Code Ruby
系列文
懶人寫寫 BOT30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言