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

Exercise solution:
How private are private instance variables?


It is possible for one BankAccount object to modify the balance of another BankAccount object. The version of class BankAccount shown below demonstrates this. Please notice the line

  backupAccount.balance -= amount - balance;

in the method withdraw.

Is this reasonable? Yes. Our observations pertain to objects in the running program - the dynamic situation. Our attention to firewalls (icebergs and representation independence) is oriented towards the source program - the static situation. In relation to programmers, who write the BankAccount class and related classes, it is important to enforce the discipline that the data representation of foreign classes is invisible. Without such a policy the idea of representation independence will be shipwrecked. This is a software engineering concern.

It causes no software engineering problems if one BankAccount object can modify the data of another BankAccount object in the way sketched above.

Here follows my programmed solution to this exercises:

using System;

public class BankAccount {

   private double interestRate;
   private string owner;
   private double balance;
   private BankAccount backupAccount;

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

   public BankAccount(string owner, double interestRate): 
     this(owner, interestRate, null){
   }   

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

   public double Balance () {
      return balance;
   }

   public void withdraw (double amount) {
      if (balance >= amount)
         balance -= amount;
      else if (balance < amount && backupAccount != null){
         backupAccount.balance -= amount - balance;
         balance = 0; 
      }
      else throw new Exception("Help!");
   }

   public void deposit (double amount) {
      balance += amount;
   }

   public void addInterests() {
      balance = balance + balance * interestRate;
   }    

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