Object-Oriented Design & Patterns

Cay S. Horstmann

Chapter 3

Guidelines for Class Design

Chapter Topics

Date Classes in Standard Library

Methods of the Date class

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

Points in Time

.

The GregorianCalendar Class

Date Handling in the Java Library

.

Designing a Day Class

Designing a Day Class

Designing a Day Class

.

Designing a Day Class

Implementing a Day Class

Implementing a Day Class

Second Implementation

Third Implementation

The Importance of Encapsulation

Accessors and Mutators

Don't Supply a Mutator for every Accessor

Sharing Mutable References

Sharing Mutable References

Sharing Mutable References

.

Final Instance Fields

Separating Accessors and Mutators

Separating Accessors and Mutators

Side Effects

Side Effects

Side Effects

Law of Demeter

Law of Demeter

Quality of Class Interface

Cohesion

Completeness

Convenience

Clarity

Clarity

Consistency

Consistency

Programming by Contract

Preconditions

Preconditions

Preconditions

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

Circular Array Implementation

Inefficient Shifting of Elements

.

A Circular Array

.

Wrapping around the End

.

Preconditions

Assertions

Assertions

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

Exceptions in the Contract

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

Postconditions

Class Invariants

Class Invariants

Unit Testing

JUnit

.

JUnit

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

JUnit

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