Skip to content

Instantly share code, notes, and snippets.

@shey
Forked from jessemiller/bank.py
Created August 10, 2010 02:31
Show Gist options
  • Save shey/516560 to your computer and use it in GitHub Desktop.
Save shey/516560 to your computer and use it in GitHub Desktop.
Refactoring buliders using python dicts
class Account():
def __init__(self):
self.balance = 0
self.currency = 'CAD'
self.overdraft = False
def make_deposit(self, amount):
"""imagine a boat load of business logic that would make this useful"""
pass
def make_withdrawl(self, amount):
"""imagine a boat load of business logic that would make this useful"""
pass
def calculate_bank_fees(self):
"""imagine a boat load of business logic that would make this useful"""
pass
class Banker():
def transfer(self, from_account, to_account, amount):
return False #again this would be actual business logic
from bank import Account
def anAccount():
return AccountBuilder(100, 'CAD', False)
class AccountBuilder:
def __init__(self, balance, currency, overdraft):
self.balance = balance
self.currency = currency
self.overdraft = overdraft
def with_(self, **overrides):
self.__dict__.update(overrides)
return AccountBuilder(self.balance, self.currency, self.overdraft)
def build(self):
account = Account()
account.balance = self.balance
account.currency = self.currency
account.overdraft = self.overdraft
return account
from bank import Banker
import builders
class TestBanker():
def test_cannot_transfer_between_account_with_different_currency(self):
account1 = builders.anAccount().with_(currency='USD').with_(balance=200).build()
account2 = builders.anAccount().with_(currency='CAD').build()
sut = Banker()
assert sut.transfer(account1, account2, 100) == False
def test_cannot_transfer_more_money_than_you_have_if_no_overdraft(self):
account1 = builders.anAccount().with_(balance=100).build()
account2 = builders.anAccount().build()
sut = Banker()
assert sut.transfer(account1, account2, 200) == False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment