Chapter Topics - Designing Effective Classes

Encapsulation: Key Feature of OO

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 - The 6 (5) C's

Cohesion

Completeness

Convenience

Clarity

Clarity

Consistency

Consistency

Programming by Contract

Preconditions

Preconditions

Precondition Example

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

Circular Array Implementation

Inefficient Shifting of Elements

.

A Circular Array

.

Wrapping around the End

.

Preconditions Must be Checkable

Assertions

Assertions Example

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

Exceptions in the Contract

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

Postconditions

Class Invariants

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);
assert d2.daysFrom(d1) == n;
}

  • Example: