©2010 Felleisen, Proulx, et. al.

7  Circular Data; State Change

7.1  Circularly Referential Data

In this part we’ll visit a familiar concept where circular data exists – namely, lists of friends , or buddy lists. These buddy lists could be IM buddy lists, ICQ buddy lists, or lists of friends on social networks. Intuitively a buddy list is just a username and a list of other buddies; the latter part is where we get circularity. So, start by working with the following files:

  1. Create a project LabBuddies and import the five files listed above into the default package. Add the tester.jar library to the project as you have done before.

    All errors should have disappeared and you should be able to run the project.

  2. Before we can design any methods for the lists of buddies, we need to be able to make examples of buddy lists.

    Design the method add that adds a buddy to one person’s buddy list.

  3. Add any additional methods you may need to make sure you can represent the following circle of buddies:

    • Ann’s buddies are Bob and Cole

    • Bob’s buddies are Ann and Ed and Hank

    • Cole’s buddy is Dan

    • Dan’s buddy is Cole

    • Ed’s buddy is Fay

    • Fay’s buddies are Ed and Gabi

    • Gabi’s buddies are Ed and Fay

    • Hank does not have any buddies

    • Jan’s buddies are Kim and Len

    • Kim’s buddies are Jan and Len

    • Len’s buddies are Jan and Kim

    If someone wants to invite a lot of friends to a party, he or she calls all people on his or her list of buddies, and asks them to invite their friends (buddies) as well, and ask their friends to invite any of their friends as well (anyone that can be reached through this network of friends. We call those on the person’s buddy list the direct buddies and the others that will also be invited to the party the distant buddies.

    Now we would like to ask some pretty common questions. For each question design the method that will find the answer. The purpose statements and the headers for the methods are already given:

  4. Does this person have another person as a direct friend?

    // returns true if this Person has that as a direct buddy
    boolean hasDirectBuddy(Person that)
    

  5. How many direct buddies do the two persons have in common?

    // returns the number of people that are direct buddies 
    // of both this and that person
    int countCommonBuddies(Person that) 
    

  6. Will the given person be invited to a party organized by someone?

    // will the given person be invited to a party 
    // organized by this person?
    boolean hasDistantBuddy(Person that)
    

  7. Homework Assignment

    How many people will be at the party if all those a person invites (directly or indirectly) show up?

    // returns the number of people who will show up at the party 
    // given by this person
    int partyCount()
    

    Follow the Design Recipe!

7.2  Mutating Object State

Goals

Today we touch the void. We will focus on the following four topics:

Rather than looking for just one correct solution to a problem, we will examine several possible ways of dealing with a problem and try to compare the solutions.

The Problem

We will work with bank accounts: checking, savings, or credit line. The bank has a list of these accounts and the customer may deposit some money or withdraw some money. Checking accounts require that the customer keeps a minimum balance, and so never withdraws all money in the account. Credit line records the balance as the amount currently owed, and it also remembers the maximum the customer can borrow. Customer can withdraw money, if adding the desired amount does not increase the balance owed to be above the maximum limit. When the customer deposits money to the credit line account, it decreases the amount owed by the deposited amount. Customer cannot overpay the debt in the credit line.

Methods that effect a simple state change

  1. Create a Java Project and add following files to it’s source directory.

    * Account.java

    * Checking.java

    * Savings.java

    * Credit.java

    * Bank.java

    * AccountList.java

    * Examples.java

  2. Make several examples of data for Checking, Savings, and Credit Accounts.

  3. Describe to your partner several scenarios of making deposits and withdrawals, to make sure you know when the transaction cannot be completed.

  4. Add the method deposit to the abstract class Account and implement it in all subclasses:

    //EFFECT: Add the given amount to this account
    //Return the new balance
    int deposit(int amount);
    

    When doing so we encounter several problems:

    • Question: How do we signal that the transaction cannot be completed?

      Answer: Throw a RuntimeException changing appropriately the following code:

      throw new RuntimeException(
                "Balance too low: " + this.balance);
      

      Make the message meaningful. You may add to the message some information about the account that caused the problem - the customer name, or the current balance available, or how much more would there need to be in the account for the transaction to go through.

    • Question: How do we test that the method will throw the expected exception with the expected message?

      Answer: Suppose the method invocation:

         this.bobAcct.withdraw(1000)

      throws a RuntimeException with the message:

         "1000 is not available".

      The test would then be:

      t.checkException(
        "Testing withdrawal from checking",  
        new RuntimeException("1000 is not available"), 
        this.bobAcct,
        "withdraw",
        1000);
      

      The first argument is a String that describes what we are testing — it is optional and can be omitted. The second argument defines the Exception our method invocation should throw. The third argument is the instance that invokes the method, the fourth argument is the method name, and after that we list as many arguments as the method consumes — all separated by commas. It could be no arguments, or five arguments — it does not matter. For our method that performs the deposit, it will be just the amount we wish to deposit.

    • Question: How do we test the correct method behavior when the transaction goes through?

      Answer: We look at the purpose and effect statements. Because the method produces a value as well as has an effect on the state of the object that invoked, we must test both parts.

      We first define instances of data we wish to use. We also define the method reset that initializes the values for the data we expect to work with and may change during the tests. We can then design the test as follows (assuming that the this.check1 is the instance that should invoke the method:

      //Tests the deposit methods inside certain accounts.
      void testDeposit(Tester t){
        reset();
        t.checkExpect(check1.deposit(100), 100);
        t.checkExpect(check1, 
          new Checking(0001, 100, "First Checking Account", 0));
        reset();
      }
      

      Notice that we use the reset method twice. At the start we make sure that the data we use has the correct values before the method is invoked, after the test we reset the data to the original values, so that the test would not affect any other part of the program. Sometimes these two method invocation are divided into two tasks: setup and tear-down. This is true of the setup actually prepares the data to have some special values before the method is invoked, but afterwards, we want to reset the values to more normal state.

      There are two tests we have performed. The first one is just like what we have done in the past — we compare the value produced by the method invocation with the expected value. The second test verifies that the state of the object we were modifying did indeed change as expected.

      Try the following incorrect implementations in the Checking class of this method to see why these tests are necessary:

      //EFFECT: Add the given amount to this account
      //Return the new balance
      int deposit(int amount){
        return this.balance + amount;
      }
      

      //EFFECT: Add the given amount to this account
      //Return the new balance
      int deposit(int amount){
        this.balance = balance + amount;
        return amount;
      }
      

      //EFFECT: Add the given amount to this account
      //Return the new balance
      int deposit(int amount){
        return 20 + (this.balance = balance + amount);
      }
      

      //EFFECT: Add the given amount to this account
      //Return the new balance
      int deposit(int amount){
        return this.balance = balance + amount;
      }
      

      Only one of these is correct. Notice the use of the assignment as the return value and as the value used in an arithmetic expression. The result of the assignment is always the value assigned to the identifier on the left-hand side.

      Of course, we need to test the method in every class in the union: the Savings class as well as the CreditLine class.

  5. Homework Assignment

    Add the method withdraw to the abstract class Account and implement it in all subclasses:

    // EFFECT: Withdraw the given funds from this account
    // Return the new balance
    int withdraw(int funds);
    

    Make sure your tests are defined as carefully as we have done in the previous case.

7.3  Methods that change the state of structured data

The class Bank keeps track of all accounts.

  1. Design the method openAcct to Bank that allow the customer to open a new account in the bank.

    // EFFECT: 
    // add a new account to the list of accounts kept by this bank
    void add(Account acct)
    

    Make sure you design your tests carefully.

  2. Design the method deposit that deposits the given amount to the account with the given name and account number.

    Make sure you report any problems, such as no such account, or that the transaction cannot be completed.

    Make sure you design your tests carefully.

  3. Design the method withdraw that withdraws the given amount from the account with the given name and account number.

    Make sure you report any problems, such as no such account, or that the transaction cannot be completed.

    Make sure you design your tests carefully.

  4. Homework Assignment

    Design the method removeAccount that will remove the account with the given account id and the given name from the list of accounts in a bank.

    void removeAccount(int acctNo, String name)
    

    Hint: Throw an exception if the account is not found

    Follow the Design Recipe!

Last modified: Wednesday, October 20th, 2010 1:58:44pm