Avatar of davearonson

davearonson's solution

to Bank Account in the Elixir Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Simulate a bank account supporting opening/closing, withdrawals, and deposits of money. Watch out for concurrent transactions!

A bank account can be accessed in multiple ways. Clients can make deposits and withdrawals using the internet, mobile phones, etc. Shops can charge against the account.

Create an account that can be accessed from multiple threads/processes (terminology depends on your programming language).

It should be possible to close an account; operations against a closed account must fail.

Instructions

Run the test file, and fix each of the errors in turn. When you get the first test to pass, go to the first pending or skipped test, and make that pass as well. When all of the tests are passing, feel free to submit.

Remember that passing code is just the first step. The goal is to work towards a solution that is as readable and expressive as you can make it.

Have fun!

Running tests

Execute the tests with:

$ elixir bank_account_test.exs

Pending tests

In the test suites, all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by commenting out the relevant @tag :pending with a # symbol.

For example:

# @tag :pending
test "shouting" do
  assert Bob.hey("WATCH OUT!") == "Whoa, chill out!"
end

Or, you can enable all the tests by commenting out the ExUnit.configure line in the test suite.

# ExUnit.configure exclude: :pending, trace: true

For more detailed information about the Elixir track, please see the help page.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

bank_account_test.exs

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("account.exs", __DIR__)
end

ExUnit.start()
ExUnit.configure(exclude: :pending, trace: true)

# The BankAccount module should support four calls:
#
# open_bank()
#   Called at the start of each test. Returns an account handle.
#
# close_bank(account)
#   Called at the end of each test.
#
# balance(account)
#   Get the balance of the bank account.
#
# update(account, amount)
#   Increment the balance of the bank account by the given amount.
#   The amount may be negative for a withdrawal.
#
# The initial value of the bank account should be 0.

defmodule BankAccountTest do
  use ExUnit.Case

  setup do
    account = BankAccount.open_bank()
    {:ok, account: account}
  end

  # @tag :pending
  test "initial balance is 0", %{account: account} do
    assert BankAccount.balance(account) == 0
  end

  @tag :pending
  test "incrementing and checking balance", %{account: account} do
    assert BankAccount.balance(account) == 0
    BankAccount.update(account, 10)
    assert BankAccount.balance(account) == 10
  end

  @tag :pending
  test "amount is added to balance", %{account: account} do
    assert BankAccount.balance(account) == 0
    BankAccount.update(account, 10)
    BankAccount.update(account, 10)
    assert BankAccount.balance(account) == 20
  end

  @tag :pending
  test "closing account rejects further inquiries", %{account: account} do
    assert BankAccount.balance(account) == 0
    BankAccount.close_bank(account)
    assert BankAccount.balance(account) == {:error, :account_closed}
    assert BankAccount.update(account, 10) == {:error, :account_closed}
  end

  @tag :pending
  test "incrementing balance from another process then checking it from test process", %{
    account: account
  } do
    assert BankAccount.balance(account) == 0
    this = self()

    spawn(fn ->
      BankAccount.update(account, 20)
      send(this, :continue)
    end)

    receive do
      :continue -> :ok
    after
      1000 -> flunk("Timeout")
    end

    assert BankAccount.balance(account) == 20
  end
end

account.exs

defmodule BankAccount do
  @moduledoc """
  A bank account that supports access from multiple processes.
  """

  @typedoc """
  An account handle.
  """
  @opaque account :: pid

  @doc """
  Open the bank. Makes the account available.
  """
  @spec open_bank() :: account
  def open_bank() do
    spawn(fn ->
      BankAccount.wait_for_msgs
    end)
  end

  @doc """
  Close the bank. Makes the account unavailable.
  """
  @spec close_bank(account) :: none
  def close_bank(account) do
    # this isn't actually USED in the tests, but since it's here....
    send(account, {:close})
  end

  @doc """
  Get the account's balance.
  """
  @spec balance(account) :: integer
  def balance(account) do
    send(account, {:balance, self})
    receive do
      whatever -> whatever
    end
  end

  @doc """
  Update the account's balance by adding the given amount which may be negative.
  """
  @spec update(account, integer) :: any
  def update(account, amount) do
    send(account, {:update, amount})
  end

  def wait_for_msgs(balance \\ 0) do
    receive do
      {:balance, asker} ->
        send(asker, balance)
        wait_for_msgs(balance)
      {:close} ->
        nil
      {:update, amount} ->
        wait_for_msgs(balance + amount)
    end
  end

end

bank_account_test.exs

if !System.get_env("EXERCISM_TEST_EXAMPLES") do
  Code.load_file("account.exs", __DIR__)
end

ExUnit.start
ExUnit.configure exclude: :pending, trace: true

# The BankAccount module should support four calls:
#
# open_bank()
#   Called at the start of each test. Returns an account handle.
#
# close_bank(account)
#   Called at the end of each test.
#
# balance(account)
#   Get the balance of the bank account.
#
# update(account, amount)
#   Increment the balance of the bank account by the given amount.
#   The amount may be negative for a withdrawal.
#
# The initial value of the bank account should be 0.

defmodule BankAccountTest do
  use ExUnit.Case

  setup do
    account = BankAccount.open_bank
    { :ok, account: account }
  end

  test "initial balance is 0", %{account: account} do
    assert BankAccount.balance(account) == 0
  end

  test "incrementing and checking balance", %{account: account} do
    assert BankAccount.balance(account) == 0
    BankAccount.update(account, 10)
    assert BankAccount.balance(account) == 10
  end

  test "amount is added to balance", %{account: account} do
    assert BankAccount.balance(account) == 0
    BankAccount.update(account, 10)
    BankAccount.update(account, 10)
    assert BankAccount.balance(account) == 20
  end

  test "incrementing balance from another process then checking it from test process", %{account: account} do
    assert BankAccount.balance(account) == 0
    this = self()
    spawn(fn ->
      BankAccount.update(account, 20)
      send(this, :continue)
    end)
    receive do
      :continue -> :ok
    after
      1000 -> flunk("Timeout")
    end
    assert BankAccount.balance(account) == 20
  end

  test "closing makes it unavailable", %{account: account} do
    assert BankAccount.balance(account) == 0
    BankAccount.close_bank(account)
    this = self
    spawn(fn ->
      BankAccount.balance(account)
      send(this, :got_balance)
    end)
    receive do
      :got_balance -> flunk("Account is still available")
    after
      # TODO: figure out how to check that the msg didn't get thru, rather than
      # wait longer than deemed needed.  this approach leads to flaky tests.
      5 -> :ok
    end

  end

end

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?