CS 2510 Spring 2012: Lab 6 - Understanding Constructors; Function Objects

copyright 2012 Felleisen, Proulx, et. al.

Goals

In the first part of this lab we will learn to design constructors that provide better user interface and at the same time assure the integrity of the data that the instances of the class represent.

In the second part of the lab we will learn to design and use function objects, the Java technique for parametrizing functional behavior.


1  Understanding Constructors.

Start a new project named Lab6-Date and import into it the file Date.java.

Standard Java asks that programmers define every public class in a file with the same name as the name of the class, followed by .java. We will now follow this convention. Define a new file in your project (in menu New -> File) and name it ExamplesDate.java. As you can guess, this will be your Examples class. Add at least three examples of valid dates to this class., and set up a Run configuration to run it.


Overloading Constructors: Assuring Data Integrity.

The data definitions at times do not capture the meaning of data and the restrictions on what values can be used to initialize different fields. For example, if we have a class that represents a date in the calendar using three integers for the day, month, and year, we know that our program is interested only in some years (maybe between the years 1500 and 2500), the month must be between 1 and 12, and the day must be between 1 and 31 (though there are additional restrictions on the day, depending on the month and whether we are in a leap year).

Suppose we make the following Date examples:

// Good dates
Date d20100228 = new Date(2010, 2, 28); // Feb 28, 2010
     Date d20091012 = new Date(2009, 10, 12);// Oct 12, 2009

// Bad date
Date dn303323 = new Date(-30, 33, 23);

Of course, the third example is just nonsense. While complete validation of dates (months, leap-years, etc...) is a course material itself, for the purposes of practicing constructors, we will simply make sure that the month is between 1 and 12, the day is between 1 and 31, and the year is between 1500 and 50000 we're thinking ahead!

Did you notice the repetition in the description of validity? It suggests we start with a few helper methods (early abstraction):

Do this quickly - do not spend much time on it - maybe do just the method validDay and leave the rest for later - for now just returniong true regardless of the input. (Such temporary method bodies are called stubs, their goal is to make the rest of program design possible.)

Now change the Date constructor to the following:

Date(int year, int month, int day){
   if(this.validYear(year))
      this.year = year;
   else
      throw new IllegalArgumentException("Invalid year");

   if(this.validMonth(month))
      this.month = month;
   else
      throw new IllegalArgumentException("Invalid month");

   if(this.validDay(day))
      this.day = day;
   else
      throw new IllegalArgumentException("Invalid day");
}

This is similar to the constructors for the Time class we saw in lectures. To signal an error or some other exceptional condition, we throw an instance of RuntimeException. We elected to use the instance of the IllegalArgumentException, which is a subclass of the RuntimeException.

If the program ever executes a statement like:

throw new ...Exception("... message ...");

Java raises the constructed exception/error. For our purposes now, this is as good as terminating the program and printing the message string.


The tester library provides methods to test constructors that should throw exceptions:

  boolean t.checkConstructorException(Exception e,
                                      String className, 
                                      ... constr args ...);

For example, the following test case verifies that our constructor throws the correct exception with the expected message, if the supplied year is 53000:

   t.checkConstructorException(
            new IllegalArgumentException("Invalid year"),
            "Date",
            53000, 12, 30);

Run your program with this test. Now change the test by providing an incorrect message, incorrect exception (e.g. NoSuchElementException), or by supplying arguments that do not cause an error, and see that the test(s) fail.

Java provides the class RuntimeException with a number of subclasses that can be used to signal different types of dynamic errors. Later we will learn how to handle errors and design new subclasses of RuntimeException to signal errors specific to our programs.

Overloading Constructors: Providing Defaults.

When entering dates for the current year it is tedious to continually enter 2011. We can provide an additional constructor that only requires the month and day, assuming the year should be 2011.

Remembering the single point of control rule, we make sure that the new overloaded constructor defers all of the work to the primary full constructor:

Date(int month, int day){
  this(2011, month, day); 
}

Add examples that use only the month and day to see that the constructor works properly. Include tests with invalid month or year as well.

Overloading Constructors: Expanding Options.

The user may want to enter the date in the form: "Oct 20 2010". To make this possible, we can add another constructor:

Date(String month, int day, int year){
  ...
}
Our first task is to convert a String that represents
a month into a number. We can do it in a helper method
getMonthNo:
// Convert a three letter month into the numeric value
int getMonthNo(String month){
  if(month.equals("Jan")){ return 1; }
  else{ if (month.equals("Feb")){ return 2; }
  else{ if (month.equals("Mar")){ return 3; }
  else{ if (month.equals("Apr")){ return 4; }
          ...
  else
    throw new IllegalArgumentException("Invalid month");
}

Our constructor can then invoke this method as follows:

   Date(String month, int day, int year){
      // Invoke the prinmary constructor, with a valid month
      this(year, 1, day);
  
      // Change the month to the given one
      this.month = this.getMonthNo(month);
   }

Complete the implementation, and check that it works correctly.


2  Abstracting with Function Objects

Download the files in Lab6.zip. The folder contains the files:

Starting with partially defined classes and examples will give you the opportunity to focus on the new material and eliminate typing in what you already know. However, make sure you understand how the class is defined, what does the data represent, and how the examples were constructed.

Create a new project Lab6-FunctionObjects and import into it all of the given files. Also add tester.jar to the Java classpath.


Introduction -- Tutorial

We start by designing three familiar methods that deal with lists of files: filterSmallerThan40000, filterNamesShorterThan4, countSmallerThan40000.

Look at the first two methods. They should only differ in the body of the conditional in the class ConsListImage. The two versions look like this:

 if (this.first.size() < 40000)
 if (this.first.name.length() < 4)

Both represent a boolean expression that depends only on the value of this.first. Think about the filter loop function in DrRacket. Its contract and header were:

;; filter: (X -> boolean) [Listof X] -> [Listof X]
;; to construct a list from all those items 
;; in alox for which p holds
(define (filter p alox)...)

The argument p was a function/predicate that consumed an item from the list (for example the first) and produced a boolean value that indicated whether the item is acceptable.

Java does not allow us to use functions or methods as arguments. To get around this problem we need to go through several steps:

The file Diagram.txt shows the class diagram for these classes and interfaces. It introduces a dotted line to indicate that the argument for a method is an instance of another class or interface.

Make sure you view the image using a fixed-width font.


Practice

We will now practice the use of function objects. The only purpose for defining the class SmallImageFile is to implement one method that determines whether the given ImageFile object has the desired property (a predicate method). An instance of this class can then be used as an argument to a method that deals with ImageFiles.

  1. Start with defining in the ExamplesImageFile class the missing tests for the class SmallImageFile.

  2. Design the method allSmallerThan40000 that determines whether all items in a list are smaller that 40000 pixels. The method should take an instance of the class SmallImageFile as an argument.

  3. We now want to determine whether the name in the given ImageFile object is shorter than 4. Design the class NameShorterThan4 that implements the ISelectImageFile interface with an appropriate predicate method.

    Make sure in the class ExamplesImageFile you define an instance of this class and test the method.

  4. Design the method allNamesShorterThan4 that determines whether all items in a list have a name that is shorter than 4 characters. The method should take an instance of the class NameShorterThan4 as an argument.

  5. Design the method allSuchImageFile that that determines whether all items in a list satisfy the predicate defined by the select method of a given instance of the type ISelectImageFile.

    Note: This resembles the andmap function in DrRacket. In the ExamplesImageFile class test this method by abstracting over the method allSmallerThan40000 and the method allNamesShorterThan4.

  6. Design the class GivenKind that implements the ISelectImageFile interface with a method that produces true for all ImageFiles that are of the given kind. The desired kind is given as a parameter to the constructor, and so is specified when a new instance of the class GivenKind is created.

    Hint: Add a field to represent the desired kind to the class GivenKind.

  7. In the ExamplesImageFile class use the method allSuch and the class GivenKind to determine whether all files in a list are jpg files. This should be written as a test case for the method allSuchImageFile.

    Do it again, but now ask about the gif files.

  8. If you have some time left, design the method filterImageFile that produces a list of all ImageFiles that satisfy the ISelectImageFile predicate. Test it with as many of your predicates as you can.

  9. Follow the same steps as above to design the method anySuchImageFile that that determines whether there is an item a list that satisfies the predicate defined by the select method of a given instance of the type ISelectImageFile.

  10. Finish the work at home and save it in your portfolio.

Food for thought: Think how this program would be different if we have instead worked with lists of Books, or lists of Shapes.


Last modified: Mon Feb 13 16:05:26 EST 2012