Created
February 19, 2015 21:45
-
-
Save mutablestate/1565be7a35d2af60b7e6 to your computer and use it in GitHub Desktop.
Early exit example with multiple clause function (for Thailand Developers Elixir slack channel)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Account do | |
defstruct id: nil, balance: 0 | |
def withdraw(account_id, amount) do | |
account_id | |
|> find | |
|> make_withdrawal(amount) | |
end | |
defp find(account_id) do | |
_fetch_account(db_query(account_id)) | |
end | |
defp _fetch_account(nil) do | |
raise ArgumentError, message: "Account does not exist!" | |
end | |
defp _fetch_account(account), do: account | |
defp db_query(account_id) do | |
if account_id == 541 do | |
%Account{id: 541, balance: 1000} | |
else | |
nil | |
end | |
end | |
defp make_withdrawal(account, amount) do | |
if account.balance > amount do | |
new_balance = account.balance - amount | |
"Your new balance is #{new_balance}" | |
else | |
"Insufficient funds!" | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule AccountTest do | |
use ExUnit.Case, async: true | |
test "withdraw from account with sufficient funds" do | |
assert Account.withdraw(541, 500) == "Your new balance is 500" | |
end | |
test "withdrawal from account with insuffucient funds" do | |
assert Account.withdraw(541, 1000) == "Insufficient funds!" | |
end | |
test "non-existing account raises error" do | |
assert_raise ArgumentError, "Account does not exist!", fn -> | |
Account.withdraw(2, 500) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment