Avatar of turnkey-commerce

turnkey-commerce's solution

to Bank Account in the C# Track

Published at Sep 07 2019 · 0 comments
Instructions
Test suite
Solution

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!

Hints

This exercise requires you to handle data related to currency and money. A normal approuch is to use the Decimal struct to store currency values. Note though that you then only store the numeric value of a currency.

Running the tests

To run the tests, run the command dotnet test from within the exercise directory.

Initially, only the first test will be enabled. This is to encourage you to solve the exercise one step at a time. Once you get the first test passing, remove the Skip property from the next test and work on getting that test passing. Once none of the tests are skipped and they are all passing, you can submit your solution using exercism submit BankAccount.cs

Further information

For more detailed information about the C# track, including how to get help if you're having trouble, please visit the exercism.io C# language page.

BankAccountTest.cs

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;

public class BankAccountTest
{
    [Fact]
    public void Returns_empty_balance_after_opening()
    {
        var account = new BankAccount();
        account.Open();

        Assert.Equal(0, account.Balance);
    }

    [Fact(Skip = "Remove to run test")]
    public void Check_basic_balance()
    {
        var account = new BankAccount();
        account.Open();

        var openingBalance = account.Balance;

        account.UpdateBalance(10);
        var updatedBalance = account.Balance;

        Assert.Equal(0, openingBalance);
        Assert.Equal(10, updatedBalance);
    }

    [Fact(Skip = "Remove to run test")]
    public void Balance_can_increment_and_decrement()
    {
        var account = new BankAccount();
        account.Open();
        var openingBalance = account.Balance;

        account.UpdateBalance(10);
        var addedBalance = account.Balance;

        account.UpdateBalance(-15);
        var subtractedBalance = account.Balance;

        Assert.Equal(0, openingBalance);
        Assert.Equal(10, addedBalance);
        Assert.Equal(-5, subtractedBalance);
    }

    [Fact(Skip = "Remove to run test")]
    public void Closed_account_throws_exception_when_checking_balance()
    {
        var account = new BankAccount();
        account.Open();
        account.Close();

        Assert.Throws<InvalidOperationException>(() => account.Balance);
    }

    [Fact(Skip = "Remove to run test")]
    public void Change_account_balance_from_multiple_threads()
    {
        var account = new BankAccount();
        var tasks = new List<Task>();

        var threads = 500;
        var iterations = 100;

        account.Open();
        for (int i = 0; i < threads; i++)
        {
            tasks.Add(Task.Factory.StartNew(() =>
            {
                for (int j = 0; j < iterations; j++)
                {
                    account.UpdateBalance(1);
                    account.UpdateBalance(-1);
                }
            }));
        }
        Task.WaitAll(tasks.ToArray());

        Assert.Equal(0, account.Balance);
    }
}
using System;

public class BankAccount
{
    private readonly object _balanceLock = new object();

    private decimal _balance;
    public decimal Balance
    {
        get { 
            if (!_isOpen) {
                throw new InvalidOperationException();
            }
            return _balance; 
        }
        set { _balance = value; }
    }

    private bool _isOpen;

    public void Open()
    {
        Balance = 0;
        _isOpen = true;
    }

    public void Close()
    {
        _isOpen = false;
    }

    public void UpdateBalance(decimal change)
    {
        lock(_balanceLock) {
            Balance += change;
        }
    }
}

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?