Sonntag, 22. März 2015

Mark dangerous Ruby methods!

Methods that perform a permanent change to the object itself are potentially dangerous. That is why those methods should be marked with an exclamation mark at the end.
For example:
class BankAccount
  attr_accessor :amount
  def initialize amount
    @amount = amount
  end

  def withdraw_money amount
    @amount -= amount
  end
end
should be refactored to:
class BankAccount
  attr_accessor :amount
  def initialize amount
    @amount = amount
  end

  def withdraw_money! amount
    @amount -= amount
  end
end
and using it makes definitely clear, that the money is withdrawn permanently:
bank_account = BankAccount.new 1000
bank_account.withdraw_money! 200
=> 800
person.amount
=> 800

Supported by Ruby 2.1.1

Keine Kommentare:

Kommentar veröffentlichen