契約によるプログラミング
プログラムやソフトウェアのモジュールが互いにどのように動作するかを「契約」によって定義し、その契約に基づいてコードを設計・実装する方法論
契約の内容には、関数やメソッドが期待する条件(前提条件)、その実行結果として保証する条件(後提条件)、そしてモジュールやクラス全体で満たすべき不変条件(不変条件)が含まれる
code:rb
class BankAccount
attr_reader :balance
def initialize(balance)
# 前提条件: 初期残高はゼロ以上である必要がある
raise ArgumentError, "Initial balance must be non-negative" if balance < 0
@balance = balance
end
def withdraw(amount)
# 前提条件: 引き出す金額は正の数でなければならない
raise ArgumentError, "Withdraw amount must be positive" if amount <= 0
# 前提条件: 残高が引き出す金額以上でなければならない
raise ArgumentError, "Insufficient funds" if amount > @balance
@balance -= amount
# 後提条件: 残高は常にゼロ以上であることを保証
raise "Balance invariant violated" if @balance < 0
end
def deposit(amount)
# 前提条件: 預け入れ金額は正の数でなければならない
raise ArgumentError, "Deposit amount must be positive" if amount <= 0
@balance += amount
end
end