SE450: Horstmann Chapter 3

Contents [0/57]

Object-Oriented Design & Patterns [1/57]
Chapter Topics [2/57]
Date Classes in Standard Library [3/57]
Methods of the Date class [4/57]
Methods of the Date class [5/57]
Points in Time [6/57]
The GregorianCalendar Class [7/57]
Date Handling in the Java Library [8/57]
Designing a Day Class [9/57]
Designing a Day Class [10/57]
Designing a Day Class [11/57]
Designing a Day Class [12/57]
Implementing a Day Class [13/57]
Implementing a Day Class [14/57]
Second Implementation [15/57]
Third Implementation [16/57]
The Importance of Encapsulation [17/57]
Accessors and Mutators [18/57]
Don't Supply a Mutator for every Accessor [19/57]
Sharing Mutable References [20/57]
Sharing Mutable References [21/57]
Sharing Mutable References [22/57]
Final Instance Fields [23/57]
Separating Accessors and Mutators [24/57]
Separating Accessors and Mutators [25/57]
Side Effects [26/57]
Side Effects [27/57]
Side Effects [28/57]
Law of Demeter [29/57]
Law of Demeter [30/57]
Quality of Class Interface [31/57]
Cohesion [32/57]
Completeness [33/57]
Convenience [34/57]
Clarity [35/57]
Clarity [36/57]
Consistency [37/57]
Consistency [38/57]
Programming by Contract [39/57]
Preconditions [40/57]
Preconditions [41/57]
Preconditions [42/57]
Circular Array Implementation [43/57]
Inefficient Shifting of Elements [44/57]
A Circular Array [45/57]
Wrapping around the End [46/57]
Preconditions [47/57]
Assertions [48/57]
Assertions [49/57]
Exceptions in the Contract [50/57]
Postconditions [51/57]
Class Invariants [52/57]
Class Invariants [53/57]
Unit Testing [54/57]
JUnit [55/57]
JUnit [56/57]
JUnit [57/57]

Object-Oriented Design & Patterns [1/57]

Cay S. Horstmann

Chapter 3

The Object-Oriented Design Process

horstmann-oodp2

Chapter Topics [2/57]

Date Classes in Standard Library [3/57]

Methods of the Date class [4/57]

boolean after(Date other)
Tests if this date is after the specified date
boolean before(Date other) Tests if this date is before the specified date
int compareTo(Date other)
Tells  which date came before the other
long getTime()
Returns milliseconds since the epoch
(1970-01-01 00:00:00 GMT)
void setTime(long n)
Sets the date to the given number of milliseconds since the epoch

Methods of the Date class [5/57]

Points in Time [6/57]

.

The GregorianCalendar Class [7/57]

Date Handling in the Java Library [8/57]

.

Designing a Day Class [9/57]

Designing a Day Class [10/57]

Designing a Day Class [11/57]

.

Designing a Day Class [12/57]

Implementing a Day Class [13/57]

Implementing a Day Class [14/57]

file:horstmann/ch03_day1/Day.java [source] [doc-public] [doc-private]
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package horstmann.ch03_day1;
public class Day
{
  /**
      Constructs a day with a given year, month, and day
      of the Julian/Gregorian calendar. The Julian calendar
      is used for all days before October 15, 1582
      @param aYear a year != 0
      @param aMonth a month between 1 and 12
      @param aDate a date between 1 and 31
   */
  public Day(int aYear, int aMonth, int aDate)
  {
    year = aYear;
    month = aMonth;
    date = aDate;
  }

  /**
      Returns the year of this day
      @return the year
   */
  public int getYear()
  {
    return year;
  }

  /**
      Returns the month of this day
      @return the month
   */
  public int getMonth()
  {
    return month;
  }

  /**
      Returns the day of the month of this day
      @return the day of the month
   */
  public int getDate()
  {
    return date;
  }

  /**
      Returns a day that is a certain number of days away from
      this day
      @param n the number of days, can be negative
      @return a day that is n days away from this one
   */
  public Day addDays(int n)
  {
    Day result = this;
    while (n > 0)
    {
      result = result.nextDay();
      n--;
    }
    while (n < 0)
    {
      result = result.previousDay();
      n++;
    }
    return result;
  }

  /**
      Returns the number of days between this day and another
      day
      @param other the other day
      @return the number of days that this day is away from
      the other (>0 if this day comes later)
   */
  public int daysFrom(Day other)
  {
    int n = 0;
    Day d = this;
    while (d.compareTo(other) > 0)
    {
      d = d.previousDay();
      n++;
    }
    while (d.compareTo(other) < 0)
    {
      d = d.nextDay();
      n--;
    }
    return n;
  }

  /**
      Compares this day with another day.
      @param other the other day
      @return a positive number if this day comes after the
      other day, a negative number if this day comes before
      the other day, and zero if the days are the same
   */
  private int compareTo(Day other)
  {
    if (year > other.year) return 1;
    if (year < other.year) return -1;
    if (month > other.month) return 1;
    if (month < other.month) return -1;
    return date - other.date;
  }

  /**
      Computes the next day.
      @return the day following this day
   */
  private Day nextDay()
  {
    int y = year;
    int m = month;
    int d = date;

    if (y == GREGORIAN_START_YEAR
        && m == GREGORIAN_START_MONTH
        && d == JULIAN_END_DAY)
      d = GREGORIAN_START_DAY;
    else if (d < daysPerMonth(y, m))
      d++;
    else
    {
      d = 1;
      m++;
      if (m > DECEMBER)
      {
        m = JANUARY;
        y++;
        if (y == 0) y++;
      }
    }
    return new Day(y, m, d);
  }

  /**
      Computes the previous day.
      @return the day preceding this day
   */
  private Day previousDay()
  {
    int y = year;
    int m = month;
    int d = date;

    if (y == GREGORIAN_START_YEAR
        && m == GREGORIAN_START_MONTH
        && d == GREGORIAN_START_DAY)
      d = JULIAN_END_DAY;
    else if (d > 1)
      d--;
    else
    {
      m--;
      if (m < JANUARY)
      {
        m = DECEMBER;
        y--;
        if (y == 0) y--;
      }
      d = daysPerMonth(y, m);
    }
    return new Day(y, m, d);
  }

  /**
      Gets the days in a given month
      @param y the year
      @param m the month
      @return the last day in the given month
   */
  private static int daysPerMonth(int y, int m)
  {
    int days = DAYS_PER_MONTH[m - 1];
    if (m == FEBRUARY && isLeapYear(y))
      days++;
    return days;
  }

  /**
      Tests if a year is a leap year
      @param y the year
      @return true if y is a leap year
   */
  private static boolean isLeapYear(int y)
  {
    if (y % 4 != 0) return false;
    if (y < GREGORIAN_START_YEAR) return true;
    return (y % 100 != 0) || (y % 400 == 0);
  }

  private int year;
  private int month;
  private int date;

  private static final int[] DAYS_PER_MONTH
  = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

  private static final int GREGORIAN_START_YEAR = 1582;
  private static final int GREGORIAN_START_MONTH = 10;
  private static final int GREGORIAN_START_DAY = 15;
  private static final int JULIAN_END_DAY = 4;

  private static final int JANUARY = 1;
  private static final int FEBRUARY = 2;
  private static final int DECEMBER = 12;
}





file:horstmann/ch03_day1/DayTester.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
package horstmann.ch03_day1;
public class DayTester
{
  public static void main(String[] args)
  {
    Day today = new Day(2001, 2, 3); // February 3, 2001
    Day later = today.addDays(999);
    System.out.println(later.getYear()
        + "-" + later.getMonth()
        + "-" + later.getDate());
    System.out.println(later.daysFrom(today)); // Prints 999
  }
}

Second Implementation [15/57]

file:horstmann/ch03_day2/Day.java [source] [doc-public] [doc-private]
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package horstmann.ch03_day2;
public class Day
{
  /**
      Constructs a day with a given year, month, and day
      of the Julian/Gregorian calendar. The Julian calendar
      is used for all days before October 15, 1582
      @param aYear a year != 0
      @param aMonth a month between 1 and 12
      @param aDate a date between 1 and 31
   */
  public Day(int aYear, int aMonth, int aDate)
  {
    julian = toJulian(aYear, aMonth, aDate);
  }

  /**
      Returns the year of this day
      @return the year
   */
  public int getYear()
  {
    return fromJulian(julian)[0];
  }

  /**
      Returns the month of this day
      @return the month
   */
  public int getMonth()
  {
    return fromJulian(julian)[1];
  }

  /**
      Returns the day of the month of this day
      @return the day of the month
   */
  public int getDate()
  {
    return fromJulian(julian)[2];
  }

  /**
      Returns a day that is a certain number of days away from
      this day
      @param n the number of days, can be negative
      @return a day that is n days away from this one
   */
  public Day addDays(int n)
  {
    return new Day(julian + n);
  }

  /**
      Returns the number of days between this day and another day.
      @param other the other day
      @return the number of days that this day is away from
      the other (>0 if this day comes later)
   */
  public int daysFrom(Day other)
  {
    return julian - other.julian;
  }

  private Day(int aJulian)
  {
    julian = aJulian;
  }

  /**
      Computes the Julian day number of the given day.
      @param year a year
      @param month a month
      @param date a day of the month
      @return The Julian day number that begins at noon of
      the given day
      Positive year signifies CE, negative year BCE.
      Remember that the year after 1 BCE was 1 CE.

      A convenient reference point is that May 23, 1968 noon
      is Julian day number 2440000.

      Julian day number 0 is a Monday.

      This algorithm is from Press et al., Numerical Recipes
      in C, 2nd ed., Cambridge University Press 1992
   */
  private static int toJulian(int year, int month, int date)
  {
    int jy = year;
    if (year < 0) jy++;
    int jm = month;
    if (month > 2) jm++;
    else
    {
      jy--;
      jm += 13;
    }
    int jul = (int) (java.lang.Math.floor(365.25 * jy)
        + java.lang.Math.floor(30.6001 * jm) + date + 1720995.0);

    int IGREG = 15 + 31 * (10 + 12 * 1582);
    // Gregorian Calendar adopted Oct. 15, 1582

    if (date + 31 * (month + 12 * year) >= IGREG)
      // Change over to Gregorian calendar
    {
      int ja = (int) (0.01 * jy);
      jul += 2 - ja + (int) (0.25 * ja);
    }
    return jul;
  }

  /**
      Converts a Julian day number to a calendar date.

      This algorithm is from Press et al., Numerical Recipes
      in C, 2nd ed., Cambridge University Press 1992

      @param j  the Julian day number
      @return an array whose 0 entry is the year, 1 the month,
      and 2 the day of the month.
   */
  @SuppressWarnings("cast")
  private static int[] fromJulian(int j)
  {
    int ja = j;

    int JGREG = 2299161;
    // The Julian day number of the adoption of the Gregorian calendar

    if (j >= JGREG)
      // Cross-over to Gregorian Calendar produces this correction
    {
      int jalpha = (int) (((float) (j - 1867216) - 0.25)
          / 36524.25);
      ja += 1 + jalpha - (int) (0.25 * jalpha);
    }
    int jb = ja + 1524;
    int jc = (int) (6680.0 + ((float) (jb - 2439870) - 122.1)
        / 365.25);
    int jd = (int) (365 * jc + (0.25 * jc));
    int je = (int) ((jb - jd) / 30.6001);
    int date = jb - jd - (int) (30.6001 * je);
    int month = je - 1;
    if (month > 12) month -= 12;
    int year = jc - 4715;
    if (month > 2) --year;
    if (year <= 0) --year;
    return new int[] { year, month, date };
  }

  private int julian;
}





Third Implementation [16/57]

file:horstmann/ch03_day3/Day.java [source] [doc-public] [doc-private]
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package horstmann.ch03_day3;
public class Day
{
  /**
      Constructs a day with a given year, month, and day
      of the Julian/Gregorian calendar. The Julian calendar
      is used for all days before October 15, 1582
      @param aYear a year != 0
      @param aMonth a month between 1 and 12
      @param aDate a date between 1 and 31
   */
  public Day(int aYear, int aMonth, int aDate)
  {
    year = aYear;
    month = aMonth;
    date = aDate;
    ymdValid = true;
    julianValid = false;
  }

  /**
      Returns the year of this day
      @return the year
   */
  public int getYear()
  {
    ensureYmd();
    return year;
  }

  /**
      Returns the month of this day
      @return the month
   */
  public int getMonth()
  {
    ensureYmd();
    return month;
  }

  /**
      Returns the day of the month of this day
      @return the day of the month
   */
  public int getDate()
  {
    ensureYmd();
    return date;
  }

  /**
      Returns a day that is a certain number of days away from
      this day
      @param n the number of days, can be negative
      @return a day that is n days away from this one
   */
  public Day addDays(int n)
  {
    ensureJulian();
    return new Day(julian + n);
  }

  /**
      Returns the number of days between this day and another
      day
      @param other the other day
      @return the number of days that this day is away from
      the other (>0 if this day comes later)
   */
  public int daysFrom(Day other)
  {
    ensureJulian();
    other.ensureJulian();
    return julian - other.julian;
  }

  private Day(int aJulian)
  {
    julian = aJulian;
    ymdValid = false;
    julianValid = true;
  }

  /**
      Computes the Julian day number of this day if
      necessary
   */
  private void ensureJulian()
  {
    if (julianValid) return;
    julian = toJulian(year, month, date);
    julianValid = true;
  }

  /**
      Converts this Julian day mumber to a calendar date if necessary.
   */
  private void ensureYmd()
  {
    if (ymdValid) return;
    int[] ymd = fromJulian(julian);
    year = ymd[0];
    month = ymd[1];
    date = ymd[2];
    ymdValid = true;
  }

  /**
      Computes the Julian day number of the given day day.

      @param year a year
      @param month a month
      @param date a day of the month
      @return The Julian day number that begins at noon of
      the given day
      Positive year signifies CE, negative year BCE.
      Remember that the year after 1 BCE is 1 CE.

      A convenient reference point is that May 23, 1968 noon
      is Julian day number 2440000.

      Julian day number 0 is a Monday.

      This algorithm is from Press et al., Numerical Recipes
      in C, 2nd ed., Cambridge University Press 1992
   */
  private static int toJulian(int year, int month, int date)
  {
    int jy = year;
    if (year < 0) jy++;
    int jm = month;
    if (month > 2) jm++;
    else
    {
      jy--;
      jm += 13;
    }
    int jul = (int) (java.lang.Math.floor(365.25 * jy)
        + java.lang.Math.floor(30.6001 * jm) + date + 1720995.0);

    int IGREG = 15 + 31 * (10 + 12 * 1582);
    // Gregorian Calendar adopted Oct. 15, 1582

    if (date + 31 * (month + 12 * year) >= IGREG)
      // Change over to Gregorian calendar
    {
      int ja = (int) (0.01 * jy);
      jul += 2 - ja + (int) (0.25 * ja);
    }
    return jul;
  }

  /**
      Converts a Julian day number to a calendar date.

      This algorithm is from Press et al., Numerical Recipes
      in C, 2nd ed., Cambridge University Press 1992

      @param j  the Julian day number
      @return an array whose 0 entry is the year, 1 the month,
      and 2 the day of the month.
   */
  @SuppressWarnings("cast")
  private static int[] fromJulian(int j)
  {
    int ja = j;

    int JGREG = 2299161;
    // The Julian day number of the adoption of the Gregorian calendar

    if (j >= JGREG)
      // Cross-over to Gregorian Calendar produces this correction
    {
      int jalpha = (int) (((float) (j - 1867216) - 0.25)
          / 36524.25);
      ja += 1 + jalpha - (int) (0.25 * jalpha);
    }
    int jb = ja + 1524;
    int jc = (int) (6680.0 + ((float) (jb - 2439870) - 122.1)
        / 365.25);
    int jd = (int) (365 * jc + (0.25 * jc));
    int je = (int) ((jb - jd) / 30.6001);
    int date = jb - jd - (int) (30.6001 * je);
    int month = je - 1;
    if (month > 12) month -= 12;
    int year = jc - 4715;
    if (month > 2) --year;
    if (year <= 0) --year;
    return new int[] { year, month, date };
  }

  private int year;
  private int month;
  private int date;
  private int julian;
  private boolean ymdValid;
  private boolean julianValid;
}





The Importance of Encapsulation [17/57]

Accessors and Mutators [18/57]

Don't Supply a Mutator for every Accessor [19/57]

Sharing Mutable References [20/57]

Sharing Mutable References [21/57]

Sharing Mutable References [22/57]

.

Final Instance Fields [23/57]

Separating Accessors and Mutators [24/57]

Separating Accessors and Mutators [25/57]

Side Effects [26/57]

Side Effects [27/57]

Side Effects [28/57]

Law of Demeter [29/57]

Law of Demeter [30/57]

Quality of Class Interface [31/57]

Cohesion [32/57]

Completeness [33/57]

Convenience [34/57]

Clarity [35/57]

Clarity [36/57]

Consistency [37/57]

Consistency [38/57]

Programming by Contract [39/57]

Preconditions [40/57]

Preconditions [41/57]

Preconditions [42/57]

/**
Remove message at head
@return the message at the head
@precondition size() > 0
*/
Message remove()
{
return elements.remove(0);
}

Circular Array Implementation [43/57]

file:horstmann/ch03_queue/MessageQueue.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package horstmann.ch03_queue;
/**
    A first-in, first-out bounded collection of messages.
 */
public class MessageQueue
{
  /**
       Constructs an empty message queue.
       @param capacity the maximum capacity of the queue
       <p><b>Precondition:</b> capacity > 0
   */
  public MessageQueue(int capacity)
  {
    elements = new Message[capacity];
    count = 0;
    head = 0;
    tail = 0;
  }

  /**
       Remove message at head.
       @return the message that has been removed from the queue
       <p><b>Precondition:</b> size() > 0
   */
  public Message remove()
  {
    Message r = elements[head];
    head = (head + 1) % elements.length;
    count--;
    return r;
  }

  /**
       Append a message at tail.
       @param aMessage the message to be appended
       <p><b>Precondition:</b> !isFull();
   */
  public void add(Message aMessage)
  {
    elements[tail] = aMessage;
    tail = (tail + 1) % elements.length;
    count++;
  }

  /**
       Get the total number of messages in the queue.
       @return the total number of messages in the queue
   */
  public int size()
  {
    return count;
  }

  /**
       Checks whether this queue is full
       @return true if the queue is full
   */
  public boolean isFull()
  {
    return count == elements.length;
  }

  /**
       Get message at head.
       @return the message that is at the head of the queue
       <p><b>Precondition:</b> size() > 0
   */
  public Message peek()
  {
    return elements[head];
  }

  private Message[] elements;
  private int head;
  private int tail;
  private int count;
}

Inefficient Shifting of Elements [44/57]

.

A Circular Array [45/57]

.

Wrapping around the End [46/57]

.

Preconditions [47/57]

Assertions [48/57]

Assertions [49/57]

public Message remove() 
{
assert count > 0 : "violated precondition size() > 0";
Message r = elements[head];
. . .
}

Exceptions in the Contract [50/57]

/**
. . .
@throws NoSuchElementException if queue is empty
*/
public Message remove()
{
if (count == 0)
throw new NoSuchElementException();
Message r = elements[head];
. . .
}

Postconditions [51/57]

Class Invariants [52/57]

Class Invariants [53/57]

Unit Testing [54/57]

JUnit [55/57]

.

JUnit [56/57]

import junit.framework.*;
public class DayTest extends TestCase
{
public void testAdd() { ... }
public void testDaysBetween() { ... }
. . .
}

JUnit [57/57]

public void testAdd()
{
Day d1 = new Day(1970, 1, 1);
int n = 1000;
Day d2 = d1.addDays(n);
assertTrue(d2.daysFrom(d1) == n);
}

Revised: 2007/09/11 16:24