Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
The method LogTransaction in class BankAccount


Here is my version of BankAccount class with logging:

using System;

public enum AccountTransaction {Withdrawing, Depositing, Interests};

public class BankAccount {

   private double interestRate;
   private string owner;
   private decimal balance;

   const int logMaxSize = 1000;
   private static LogEntry[] log = new LogEntry[logMaxSize];
   private static int nextLogIndex = 0;

   public BankAccount(string owner): this(owner, 0.0) {
   }

   public BankAccount(string owner, double interestRate) {
     this.interestRate = interestRate;
     this.owner = owner; 
     this.balance = 0.0M;
   }   

   public decimal Balance () {
     return balance;
   }

   private void LogTransaction(AccountTransaction kind, decimal amount){
      if (nextLogIndex < logMaxSize){
        log[nextLogIndex] = new LogEntry(this, kind, DateTime.Now, amount);
        nextLogIndex++;
      } else
        throw new Exception("Problems");
   }

   public static void FullLogHistory(){
     for(int i = 0; i < nextLogIndex; i++)
       Console.WriteLine(log[i]);
   }

   public void Withdraw (decimal amount) {
     this.LogTransaction(AccountTransaction.Withdrawing, amount);
     balance -= amount;
   }

   public void Deposit (decimal amount) {
     this.LogTransaction(AccountTransaction.Depositing, amount);
     balance += amount;
   }

   public void AddInterests() {
     decimal interests = balance * (decimal)interestRate;
     this.LogTransaction(AccountTransaction.Interests,  interests);
     balance += interests;
   }    

   public override string ToString() {
     return owner + "'s account holds " +
           + balance + " kroner";
   }
} 

public class LogEntry{
  private BankAccount ba;
  private AccountTransaction kind;
  private DateTime timestamp;
  private decimal amount;

  public LogEntry(BankAccount ba, AccountTransaction kind, DateTime t, decimal amount){
    this.ba = ba;
    this.kind = kind;
    this.timestamp = t;
    this.amount = amount;
  }

  public override string ToString(){
    return "LogEntry " + kind + ": " + amount;
  }
} 

Note to the solution: Instead of passing the current time as a parameter to LogTransaction, I found it more reasonable to capture the time inside the body of LogTransaction.