Skip to main content

CSE 331: Design Patterns 2

lecture

Course motto: Your job is to deliver code that you know works.

Lecture 20 began a catalog of design patterns. A design pattern, in that lecture's words, is a solution to a design problem that comes up again and again, written down so that others can reuse it. Lecture 20 met three patterns, and asked one question of each: once we use the pattern, what does javac check for us?

  • The static factory method, User.from. User's constructor is private, so javac checks at every compile that no client makes a User any other way.
  • The Factory Method, emptyQueue in the help queue's tests. javac checks nothing new.
  • The singleton, OfficeQueue. javac checks that no client makes a second queue.

Design Patterns, the book Lecture 20 took its definition from, sorts patterns into three kinds by their purpose. (Its four authors are known as the Gang of Four.)1 Here are the three kinds, each with the patterns this course covers:

  • Creational patterns are about making objects: the static factory method, the Factory Method, and the singleton, from Lecture 20, and interning and the builder, today.
  • Structural patterns are about how objects are put together from other objects: the adapter, the decorator, and the proxy, today.
  • Behavioral patterns are about how objects divide up work and talk to each other. They come on December 2.

Of each pattern we ask what javac checks, and what a reader or a test has to establish instead.

Interning

Lecture 20 showed what a constructor cannot do. A constructor returns a new object of its class, or it throws. A static factory method has no such limit, so it may return an object that already exists.2 Here is a program that asks four questions about objects the JDK hands out. Each line compares two expressions with ==, which is true only when the two refer to the same object:

Sharing.java
1
2
3
4
5
6
7
8
9
/** Asks whether two expressions give the same object, with ==. */
public class Sharing {
    public static void main(String[] args) {
        System.out.println(Boolean.valueOf(true) == Boolean.valueOf(true));
        System.out.println(Integer.valueOf(100) == Integer.valueOf(100));
        System.out.println("hello" == new String("hello"));
        System.out.println("hello" == new String("hello").intern());
    }
}

Before you read on, write down whether each line prints true or false. Here is the run:

$ java Sharing
true
true
false
true

Here is why, one line at a time:

  • Line 4. Boolean.valueOf is a static factory method. Its documentation promises that it returns the one object Boolean.TRUE whenever its argument is true.3 So the two calls return one object.
  • Line 5. Integer.valueOf is a static factory method too. Its documentation promises to keep one object for each int from -128 to 127. 100 is in that range, so the two calls return one object.
  • Line 6. The literal "hello" and new String("hello") hold the same characters. But new always makes a new object. So they are two objects, and == says so.
  • Line 7. intern returns the one string that the class String keeps for these characters. Every string literal is interned, so that string is the object the literal "hello" refers to.

Lines 4, 5, and 7 each hand out one shared object for a value. That is a pattern:

Definition: interning

A method interns a value if it keeps one object for that value, and returns that one object every time it is asked for the value.

"Value" here is Lecture 16's abstract value, what an object stands for. Integer.valueOf promises to intern the values from -128 to 127, and intern interns every string it is handed. What does interning gain? A program that asks for Integer.valueOf(100) a million times gets one object, not a million. And for interned strings, == and equals agree: s.intern() == t.intern() is true exactly when s.equals(t) is.

Interning is safe only for immutable objects. Recall from Lecture 14 that a class is immutable if no object of the class can change once its constructor has finished. Interning hands one object to many clients, and each client reasons as if the object were its own. If the object could change, a change made through one client would show up for all the others. Boolean, Integer, and String are immutable. No client can change a shared one, so no client can tell that it is shared, except with ==.

javac checks nothing about interning. javac accepts == between any two Integers, and it checks nothing about what valueOf returns beyond its type. Line 5 printed true because of a promise in Integer's documentation, which a reader checks and javac does not. And the promise is narrow. The documentation says that valueOf will "always cache values in the range -128 to 127, inclusive," and it leaves the other values open. So for Integer.valueOf(1000) == Integer.valueOf(1000), the documentation allows either answer. A program that compares Integers with == is known to work only for small numbers.

So compare values with equals, whether or not they are interned. Lecture 16 drew the line between the two questions. == asks whether two names refer to the same object. The question we almost always mean is whether two objects stand for the same value, and equals asks that one. Integer's equals answers it for every int.

Interning is about how many objects of a class there are. The next creational pattern takes up a different problem in making an object: a constructor whose parts are all Strings.

A builder names each part

Lecture 20's guestbook handler passed its owner where delete's asker belonged. Both were a String, so javac accepted the call, and bob could delete from ada's book. The same mistake can be made wherever a method takes two parameters of one type. A message in the guestbook is one such place. It has three parts: its author, who wrote it; its owner, whose book it is in; and its text. positional/Message.java keeps the three apart, each a String, and its constructor takes them in that order:

positional/Message.java
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private final String author;
private final String owner;
private final String text;
// RI: author, owner, and text are not null.
// AF(this) = the message text, written by the user whose login
//     is author, in the book of the user whose login is owner.

/**
 * @requires author, owner, and text are not null
 * @effects makes the message text, by author, in owner's book
 */
public Message(String author, String owner, String text) {
    this.author = author;
    this.owner = owner;
    this.text = text;
}

Its client, positional/Signing.java, has bob sign ada's book twice, in its main. Its variables asker and owner are named as the handler's were:

positional/Signing.java
 8
 9
10
11
String asker = "bob@example.com";
String owner = "ada@example.com";
System.out.println(new Message(asker, owner, "hi ada"));
System.out.println(new Message(owner, asker, "hi ada"));

Will javac accept line 11? If it does, what will the program print? Decide before reading on.

$ java Signing
bob@example.com signs ada@example.com's book: hi ada
ada@example.com signs bob@example.com's book: hi ada

javac accepted line 11, and its message has ada signing bob's book. Line 11 passes owner first, where the constructor takes the author. javac checks that a call to the constructor passes three Strings. owner and asker are both Strings, so the swapped call passes that check. Joshua Bloch, whose Effective Java was Lecture 20's source for the static factory method, describes this bug. When a client reverses two parameters of the same type, "the compiler won't complain, but the program will misbehave at runtime."4

Lecture 20's fix for the handler was a type: delete came to take a User, and javac refused a String in its place. That fix does not carry over to a message. Its author and owner could each be a User, but two Users swap exactly as two Strings do. Only a type for each role would let javac catch the swap. Bloch's own example, a food's nutrition label, has a constructor that takes six ints, servings and calories among them, and no type tells one amount from another. So today's fix is a different one: the call names each part.

Setters on the message. One way to name each part is a setter for each, on Message itself. The client makes an empty message, then calls setAuthor, setOwner, and setText. Bloch calls this the JavaBeans pattern. Two of his reasons against it apply here. First, between the empty message and the last setter, the message exists with parts unset. positional/Message.java's RI, on its line 11, says that no part is null. So for that stretch the RI is false of an object a client holds. Second, a setter assigns a field, so the fields cannot be final. A message could then change after it was signed.

A builder. A builder keeps the setters, but moves them to a second object, which makes the message once every part is set. Message.java is the same message, with the same fields and RI, made with a builder. Its constructor is now private and takes the builder:

Message.java
13
14
15
16
17
private Message(Builder builder) {
    this.author = builder.author;
    this.owner = builder.owner;
    this.text = builder.text;
}
Message.java
24
25
26
27
28
29
30
31
32
33
34
35
/** The parts of a message set so far, none at first. */
public static class Builder {
    private String author;
    private String owner;
    private String text;

    // Each method sets the part it names, then returns this
    // builder, so that a client can chain the calls.
    public Builder author(String author) {
        this.author = author;
        return this;
    }
Message.java
47
48
49
50
51
52
53
54
55
56
57
    /**
     * @return the message with the parts set
     * @throws IllegalStateException if a part is not set
     */
    public Message build() {
        if (author == null || owner == null || text == null) {
            throw new IllegalStateException("a part is not set");
        }
        return new Message(this);
    }
}

Builder is a class declared inside Message, so its full name is Message.Builder. It is declared static, so a builder belongs to no message. A client makes one with new Message.Builder() before any message exists. Its three fields start out null, since no part is set yet. Each setter returns this, the builder itself, so a client can call the next setter on what the last one returned. owner and text, on lines 37 to 45, set their parts as author does. Finally, build() checks that every part is set, and only then makes the message.

Java lets a nested class call its enclosing class's private constructor, so build() can call Message's. No code outside Message can. So every Message is made on line 55, after the check on line 52 has passed. As with Lecture 20's User, we read one class to know something about every object of it: here, that no Message has a null part. Message's fields are final again, so no message changes after build() makes it.

Signing.java signs ada's book three times with the builder. Lines 13 and 14 make the old line 11's swap, and lines 15 and 16 set no owner at all:

Signing.java
 9
10
11
12
13
14
15
16
String asker = "bob@example.com";
String owner = "ada@example.com";
System.out.println(new Message.Builder()
    .author(asker).owner(owner).text("hi ada").build());
System.out.println(new Message.Builder()
    .author(owner).owner(asker).text("hi ada").build());
System.out.println(new Message.Builder()
    .author(asker).text("hi ada").build());

Will javac accept each call? What will the program print?

$ java Signing
bob@example.com signs ada@example.com's book: hi ada
ada@example.com signs bob@example.com's book: hi ada
Exception in thread "main" java.lang.IllegalStateException: a part is not set
    at Message$Builder.build(Message.java:53)
    at Signing.main(Signing.java:16)

javac accepted all three calls. The swap on line 14 printed the same wrong line as before. What changed is the call: it now reads author(owner), so a reader of line 14 can see the mistake without opening Message.java to count parameters. The call on lines 15 and 16 compiled too, and build() refused it at run time, from line 53. Message$Builder is Java's name for the nested class, written with a dollar sign.

Definition: builder

A builder is an object that holds the parts of another object while a client sets them, one named method per part, and then makes that object with every part at once.

So which mistakes in making a Message does javac catch with the constructor, but not with the builder? Which does it catch with neither? Answer both before reading on.

  • A part left out: the constructor only. Here is a copy of positional/Signing.java whose line 11 is new Message(asker, "hi ada"), with no owner:

    $ javac Signing.java Message.java
    Signing.java:11: error: constructor Message in class Message cannot be applied to given types;
            System.out.println(new Message(asker, "hi ada"));
                               ^
      required: String,String,String
      found:    String,String
      reason: actual and formal argument lists differ in length
    1 error
    

    With the builder, the same mistake compiled. It was caught at run time, and only because build() checks. A build() without lines 52 to 54 would make a message whose owner is null, and the RI would be false of that message.

  • A swap: neither. Every part is a String, so javac accepts a swap with the constructor and with the builder. The builder's call shows the swap to a reader. Since javac does not check it, a reader of the call, or a test of it, has to.

javac checks two things in a builder's call: that each setter gets a String, and that each method's name is one Builder has. A copy of Signing.java whose line 16 calls .auther(asker) does not compile: javac says it cannot find the method.

So the builder moves a check, from javac, at every compile, to build(), only when a run reaches it. In return, a reader of the builder's call sees each part's name beside its value.

The pattern. In the four parts Lecture 20's definition gives a design pattern, with the consequences split into gains and costs:

  • Name: builder. Message.Builder is one.
  • Problem: a constructor takes many parts by position, two or more of one type, so a call can swap two and still compile.
  • Solution: a second class, with a method that names each part, and a build() that makes the object.
  • Gains: the call names each part. build() can check the parts before the object exists, so the object can be immutable, its RI true from the start.
  • Costs: a second class, to write and to read. A part left out compiles, and is caught at run time, if build() checks.

When is a builder worth a second class? Bloch suggests one when a constructor would take four or more parameters, especially when many are optional or of one type. His nutrition label has two required parts and many optional ones. His builder takes the required parts in its constructor, by position, so javac checks that they are given. It names only the optional ones. Message has fewer than four parts, and all three are required.

Wrappers, and an adapter for the help queue

A builder is about making an object. The next three patterns, the adapter, the decorator, and the proxy, are about putting objects together, and Design Patterns calls them structural patterns.5 The adapter and the decorator come first, on the help queue, and the proxy last, on the guestbook.

The help queue. Lecture 10 specified the help queue as an interface, HelpQueue, whose comment says that a student is in the queue at most once. Its method join is the one this section leans on:

HelpQueue.java
12
13
14
15
16
17
18
    /**
     * @modifies this
     * @effects adds the student at the back of the queue
     * @throws IllegalArgumentException if the student is already in
     *     the queue, and leaves the queue unchanged
     */
    void join(String netid);

Its other three methods are size, next, and waiting. next removes and returns the student at the front, and its @throws clause names NoSuchElementException if the queue is empty. waiting returns the students waiting, front first, in a new list. Lecture 20 then added HelpQueues, whose static factory method empty is the one place a program writes a queue's class:

HelpQueues.java
1
2
3
4
5
6
7
/** Makes help queues: the one place that names a queue's class. */
public class HelpQueues {
    /** @return a new help queue, with no students waiting */
    public static HelpQueue empty() {
        return new ListQueue();
    }
}

A client, such as Lecture 20's OfficeHours, asks HelpQueues.empty() for a queue and holds it as a HelpQueue. So a change to line 5 changes the queue that every such client gets, and no client's code changes.

A queue from the JDK. Java's library has a queue class, java.util.ArrayDeque. Its method addLast adds an element at the back, removeFirst removes and returns the front, and size counts. Those are a help queue's join, next, and size, under other names. So can empty return an ArrayDeque? Suppose a copy of HelpQueues.java changes line 5 to return new java.util.ArrayDeque<String>();. (HelpQueues has no imports, so the copy writes the class's full name.) Will javac accept the copy? Decide before you read the run:

$ javac HelpQueues.java
HelpQueues.java:5: error: incompatible types: ArrayDeque<String> cannot be converted to HelpQueue
        return new java.util.ArrayDeque<String>();
               ^
1 error

javac refuses it, for the reason Lecture 14 gave. The compiler accepts a B where an A is expected when B reaches A by a chain of extends and implements. It decides from those declarations alone, never from a specification. ArrayDeque's declaration never says implements HelpQueue. Methods do not enter into it: a class of our own with HelpQueue's four methods, and no implements HelpQueue, would be refused the same way. And ArrayDeque is the JDK's class, not ours, so we cannot add those words to it.

An adapter. What we need is a class with HelpQueue's interface and ArrayDeque's work. Here is one:

DequeQueue.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;

/** A help queue kept in an ArrayDeque: an adapter. */
public class DequeQueue implements HelpQueue {
    private ArrayDeque<String> deque =
        new ArrayDeque<String>();

    public int size() {
        return deque.size();
    }

    public void join(String netid) {
        if (deque.contains(netid)) {
            throw new IllegalArgumentException(netid);
        }
        deque.addLast(netid);
    }

    public String next() {
        return deque.removeFirst();
    }

    public List<String> waiting() {
        return new ArrayList<String>(deque);
    }
}

DequeQueue says implements HelpQueue on line 6, so javac accepts a DequeQueue where a HelpQueue is expected. Its field deque, on lines 7 and 8, holds the wrapped ArrayDeque, and each method passes its call on to it. size calls size, join calls addLast, and next calls removeFirst. waiting copies the deque into a new list. DequeQueue is the first of this lecture's three wrappers:

Definition: wrapper

A wrapper is an object that holds another object in a field, and does its work by calling that object's methods.

This is a different sense of the word from Lecture 6's wrapper, an OptionalInt that holds one int or none. We will call the object in the field the wrapped object. A wrapper is what Lecture 14 called composition: a class built from an object held in a field. Each of a wrapper's methods passes the call on to the wrapped object, which Lecture 14 called forwarding. Lecture 14's Square, in ComposedSquare.java, held a Rectangle in its field rect and forwarded getWidth to it.6 The three wrappers are told apart by what they keep of the wrapped object:

What the object does Its interface
adapter same changed
decorator changed same
proxy same same

"What the object does" is what its methods do. "Its interface" is the Java interface that a client of the wrapper sees.

To argue that DequeQueue satisfies HelpQueue's specification, we read two specifications: HelpQueue's, for what each method has to do, and ArrayDeque's, for what each call does. ArrayDeque's documentation says that removeFirst throws NoSuchElementException if the deque is empty, as next promises. It also says that an ArrayDeque hands out its elements from first to last, so the new list on line 26 is front first, as waiting promises.7 But no method of ArrayDeque keeps one promise: join's @throws clause. ArrayDeque's addLast adds whatever it is handed. So DequeQueue writes the check itself, on lines 15 to 17, and throws before line 18 adds anything.

Twice is a client that has ada join twice:

Twice.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
/** A student tries to join the help queue twice. */
public class Twice {
    public static void main(String[] args) {
        HelpQueue queue = HelpQueues.empty();
        queue.join("ada");
        try {
            queue.join("ada");
        } catch (IllegalArgumentException e) {
            System.out.println("refused: " + e.getMessage());
        }
        System.out.println(queue.waiting());
    }
}

With line 5 of HelpQueues as return new DequeQueue();, the second join is refused:

$ java Twice
refused: ada
[ada]

Without the check. Now suppose a copy of DequeQueue drops lines 15 to 17, so its join only calls addLast. Will javac accept the copy? What will Twice print?

$ javac DequeQueue.java

$ java Twice
[ada, ada]

javac printed nothing: it accepted the copy. Twice printed no refused line, since the second join returned normally. Then waiting showed ada twice. This run is a counterexample to join's @throws clause, and to a student is in the queue at most once. javac checked that DequeQueue has HelpQueue's four methods, with their types. Lines 15 to 17 are ours to write, and ours to confirm, by reading DequeQueue against the specification.

Definition: adapter

An adapter is a wrapper that gives the wrapped object an interface its class lacks.

Lecture 10's ListQueue also forwards to a list it holds, but it was written to be a HelpQueue, while an adapter fits a class that was written first, for other clients, as ArrayDeque was.

The pattern. In the same four parts:

  • Name: adapter. DequeQueue is one.
  • Problem: a class does the work but lacks the interface.
  • Solution: implement the interface, hold the object, and forward.
  • Gains: the class and its clients stay as they are. Only line 5 of HelpQueues changed.
  • Costs: a class to write, of which javac checks only the types.

An adapter fits when the class that does the work is one we cannot change, such as the JDK's. When the class is our own, we can write implements HelpQueue on it instead. An adapter is also thin only when the two specifications are close. A class further from HelpQueue than ArrayDeque would need more lines like 15 to 17, and javac checks none of them against the specification.

The table's rows are not sharp, either. An adapter often has to add what the adapted class lacks. DequeQueue's lines 15 to 17 add a check that ArrayDeque does not make, so DequeQueue has something of the decorator's row too.

Design Patterns also gives a second form of adapter, a class that extends the adapted class. DequeQueue holds its ArrayDeque in a field instead, the book's object adapter.5 The two forms are a choice between a wrapper and a subclass, which Composition against subclassing takes up, after the decorator.

A decorator for every help queue

The help queue now has several classes, among them Lecture 10's ListQueue, Lecture 11's FastQueue, Lecture 20's OfficeQueue, and DequeQueue. Suppose the TAs want a line printed for each join and each next, whichever class a program uses. Two calls of println in each class would do it, and every class written later would have to remember them. A decorator writes them once, in a wrapper of any HelpQueue:

LoggingQueue.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.List;

/** A help queue that prints a line for each join and next: a decorator. */
public class LoggingQueue implements HelpQueue {
    private HelpQueue inner;

    public LoggingQueue(HelpQueue inner) {
        this.inner = inner;
    }

    public int size() {
        return inner.size();
    }

    public void join(String netid) {
        inner.join(netid);
        System.out.println("log: join " + netid);
    }

    public String next() {
        String netid = inner.next();
        System.out.println("log: next " + netid);
        return netid;
    }

    public List<String> waiting() {
        return inner.waiting();
    }
}

The field inner, on line 5, has the type HelpQueue, an interface, not a class. So a LoggingQueue can hold an object of any class that implements HelpQueue. join and next forward to inner, then print a line. Now suppose inner's join throws, since the student is already in the queue. The exception leaves join at line 16, before line 17 prints. So the log never shows a join that did not happen.

Any HelpQueue, even a wrapped one. Wrapped runs a short office hour on three wrapped queues:

Wrapped.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
/** Office hours on queues wrapped in LoggingQueue. */
public class Wrapped {
    /** A student joins, and the TA helps the student at the front. */
    static void hour(HelpQueue queue) {
        queue.join("ada");
        queue.next();
    }

    public static void main(String[] args) {
        hour(new LoggingQueue(new ListQueue()));
        hour(new LoggingQueue(new FastQueue()));
        hour(new LoggingQueue(new LoggingQueue(new ListQueue())));
    }
}

hour has ada join, then calls next. Lines 10 and 11 wrap a ListQueue and a FastQueue. Line 12 wraps a LoggingQueue, which javac allows, since a LoggingQueue is a HelpQueue by line 4 of LoggingQueue.java. What does line 12 print? Work it out before you read the run:

$ java Wrapped
log: join ada
log: next ada
log: join ada
log: next ada
log: join ada
log: join ada
log: next ada
log: next ada

Lines 10 and 11 printed the same two lines, though LoggingQueue's code names neither ListQueue nor FastQueue. Line 12 printed each line twice. The outer LoggingQueue's join forwards to the inner LoggingQueue's join. That join forwards to the ListQueue, then prints. Only then does the outer join print. So decorators stack, and the inner one prints first.

What javac checks. javac accepts LoggingQueue. What has it checked, and what has it not? Write your answer before you read on.

  • Checked: LoggingQueue has HelpQueue's four methods, with their types, since line 4 says implements HelpQueue.
  • Checked: inner has each method LoggingQueue calls on it, since the type of inner is HelpQueue.
  • Not checked: that LoggingQueue satisfies HelpQueue's specification.

A tempting answer is that javac checked that the wrapper works. Lecture 14's rule said the same of every implements: javac checks the types, and nothing in the interface's Javadoc. Suppose a copy of LoggingQueue drops line 16, inner.join(netid):

$ javac LoggingQueue.java

$ java Wrapped
log: join ada
Exception in thread "main" java.util.NoSuchElementException: the queue is empty
    at ListQueue.next(ListQueue.java:22)
    at LoggingQueue.next(LoggingQueue.java:20)
    at Wrapped.hour(Wrapped.java:6)
    at Wrapped.main(Wrapped.java:10)

The log says ada joined, but nobody joined the ListQueue, so next reached an empty ListQueue and threw. (The copy is one line shorter, so its line 20 is the program's line 21.)

So we check the specification by reading the wrapper. For LoggingQueue the reading is short. Each method calls the method of inner with the same name and argument, and returns what that method returns. The only other lines print. Printing changes no parameter, and @modifies lists only the parameters a method may change, so @modifies this permits it. So LoggingQueue satisfies HelpQueue's specification whenever the class of inner does.

Definition: decorator

A decorator is a wrapper that keeps the wrapped object's interface and changes what that object does.

The pattern. In the same four parts:

  • Name: decorator. LoggingQueue is one.
  • Problem: add a behavior to every implementation of an interface.
  • Solution: implement the interface, hold any object of it, forward each call, and add the behavior.
  • Gains: one class for every implementation, chosen where an object is wrapped. Decorators stack, as on line 12 of Wrapped.
  • Costs: more objects, and a wrapper is not == to what it wraps.

In a program that gets its queues from HelpQueues, the place to wrap is line 5 of empty: return new LoggingQueue(new ListQueue()); would log every queue that empty makes.

Line 12 makes three objects for one queue. And a program that kept its own reference to the ListQueue on line 10, a different object from its LoggingQueue, could call that ListQueue's join directly, and print nothing. Design Patterns lists both costs among the decorator's consequences.5

A decorator can call only the interface's methods. So it suits a behavior written against the specification alone, as a log line is. A behavior that needs a class's own fields, such as FastQueue's set members, belongs in that class.

A decorator can take behavior away. Lecture 10's third exercise returned java.util.Collections.unmodifiableList(queue), a List that passes each read on to queue and throws UnsupportedOperationException at any attempt to change it.8

The next section writes the same log lines without a wrapper, as a subclass.

Composition against subclassing

LoggingQueue adds its log lines by holding a HelpQueue in a field. Lecture 14 showed the other way Java offers to reuse a class's code: subclassing, as SaleProduct extended Product and overrode getPrice. Here is the same logging, written as a subclass of Lecture 10's ListQueue:

LoggingListQueue.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
/** A ListQueue that prints a line for each join and next: a subclass. */
public class LoggingListQueue extends ListQueue {
    @Override
    public void join(String netid) {
        super.join(netid);
        System.out.println("log: join " + netid);
    }

    @Override
    public String next() {
        String netid = super.next();
        System.out.println("log: next " + netid);
        return netid;
    }
}

Each override runs ListQueue's own method through super, then prints its line. The class inherits size and waiting as ListQueue wrote them. A copy of Wrapped whose line 10 is hour(new LoggingListQueue()); prints the same eight lines as Wrapped.

A class with a private constructor. Lecture 20's singleton, OfficeQueue, has a private constructor, so that a program has one OfficeQueue: the one OfficeQueue.theQueue() returns. Line 10 makes it, with the private constructor on line 14:

OfficeQueue.java
10
11
12
13
14
15
16
17
18
19
20
private static final OfficeQueue THE_QUEUE = new OfficeQueue();

private List<String> queue = new ArrayList<String>();

private OfficeQueue() {
}

/** @return the queue for office hours, the same one on every call */
public static OfficeQueue theQueue() {
    return THE_QUEUE;
}

Here is a copy of LoggingListQueue.java named LoggingOfficeQueue.java, with ListQueue changed to OfficeQueue on lines 1 and 2. Will javac accept it?

$ javac LoggingOfficeQueue.java
LoggingOfficeQueue.java:2: error: OfficeQueue() has private access in OfficeQueue
public class LoggingOfficeQueue extends OfficeQueue {
       ^
1 error

LoggingOfficeQueue declares no constructor, so Java gives it one. That constructor runs OfficeQueue's.9 Only OfficeQueue's own code may run a private constructor. Lecture 20's card for the static factory method listed this among its costs: it "may rule out subclasses". A wrapper never runs that constructor. It holds the one queue: a copy of Wrapped whose line 11 is hour(new LoggingQueue(OfficeQueue.theQueue())); prints the same eight lines. But only code that holds the wrapper gets the log: any other client of OfficeQueue.theQueue() gets the queue unwrapped, the decorator's second cost again.

Here are the two classes side by side:

LoggingListQueue LoggingQueue
Logs a ListQueue any HelpQueue
Writes join and next all four methods
Relies on how ListQueue is written HelpQueue's specification
Chosen when the class is written when an object is wrapped

Writes. This row is subclassing's one gain: a subclass writes only the methods that change, where LoggingQueue has to forward size and waiting too. The adapter offered the same choice. The book's class adapter would extend ArrayDeque, inherit its size, and write the other three methods.

Relies on. LoggingQueue uses inner only through HelpQueue's methods. So the argument that LoggingQueue satisfies HelpQueue's specification uses nothing but that specification. LoggingListQueue's overrides, on the other hand, run on every call of join or next, by dynamic dispatch, even a call from inside ListQueue. Today none of ListQueue's methods calls another. Nothing in HelpQueue's specification promises that a later ListQueue keeps it so.

Here is such a later ListQueue, in queues/relies/. HelpQueue gains a method joinAll, which joins each student in a list, and ListQueue writes it with join:

relies/ListQueue.java
20
21
22
23
24
public void joinAll(List<String> netids) {
    for (String netid : netids) {
        join(netid);
    }
}

Each logging class logs joinAll as it logs join. Here is the subclass's. LoggingQueue's is the same lines, with inner for super and no @Override:

relies/LoggingListQueue.java
18
19
20
21
22
23
24
@Override
public void joinAll(List<String> netids) {
    super.joinAll(netids);
    for (String netid : netids) {
        System.out.println("log: join " + netid);
    }
}

Both has ada and bob join at once, first through a LoggingListQueue, then through a LoggingQueue around a ListQueue. What does each print?

$ java Both
subclass:
log: join ada
log: join bob
log: join ada
log: join bob
wrapper:
log: join ada
log: join bob

The subclass logged each student twice. ListQueue's joinAll called join, and dynamic dispatch ran LoggingListQueue's join, which printed. Then LoggingListQueue's own joinAll printed both lines again. The wrapper's inner is a plain ListQueue, whose join prints nothing. So the subclass's log depends on how ListQueue's joinAll is written, which HelpQueue's specification does not say. Bloch's example is a subclass of the JDK's HashSet that counted each element passed to addAll twice.10

So when is subclassing the right tool? Bloch counts it safe within one package, where the same programmers keep both classes, and for a class designed and documented to be extended.10 Even in one package, the run of Both above is what happens when ListQueue's keeper adds joinAll without rereading the subclass. Lecture 14's rule adds that the subclass must be a behavioral subtype.

The table of wrappers has one row left: the proxy, which keeps both the interface and what the object does. It comes last, on the guestbook.

A proxy for each saved book

Every book, read at the start

Lecture 19's guestbook keeps every user's book in memory, which ends with the run. So a restart empties every book, as it emptied the one book when we studied persistent data. That lecture's fix kept the book in a file, which outlasts the run, and read it back when the server started. So let's keep each user's book in a file named for the user's login, such as ada@example.com.txt for ada.

The programs are in proxy/. Book is now an interface, as the help queue was: "a specification with no fields and no method bodies." Its methods are Lecture 19's add and messages, with the same specifications. This copy leaves out delete and the owner. Here are the two declarations:

Book.java
11
12
13
14
    void add(User asker, String message) throws IOException;

    /** @return the posted messages, oldest first, in a new list */
    List<String> messages() throws IOException;

SavedBook is Lecture 19's book, with its list of messages kept in a file. Here is its constructor:

SavedBook.java
15
16
17
18
19
20
21
22
    public SavedBook(Path file) throws IOException {
        // So that a run shows when a file is read.
        System.out.println("reading " + file.getFileName());
        this.file = file;
        if (Files.exists(file)) {
            messages.addAll(Files.readAllLines(file, UTF_8));
        }
    }

Line 20 fills the list from the file, a line per message, as Lecture 18's constructor did. Line 17 is there for the runs.

Books makes a book for each file in a directory:

Books.java
13
14
15
16
17
18
19
20
21
    public Books(Path dir) throws IOException {
        try (Stream<Path> files = Files.list(dir)) {
            for (Path file : files.sorted().toList()) {
                String name = file.getFileName().toString();
                String login = name.replaceFirst("[.]txt$", "");
                books.put(login, new SavedBook(file));
            }
        }
    }

Files.list gives the paths of the directory's files, which line 15 visits in order of name. Line 17 cuts .txt off each name to get the login. bookOf is Lecture 19's.

Startup does what the guestbook would do at its start, then asks for ada's messages twice, as two requests from her would:

Startup.java
10
11
12
13
14
15
16
    public static void main(String[] args) throws IOException {
        Books books = new Books(Path.of("books"));
        System.out.println("started");
        Book book = books.bookOf("ada@example.com").get();
        System.out.println(book.messages());
        System.out.println(book.messages());
    }

The directory books/ holds two files, ada's and bob's. Ada asks for her book. Which files are read, and when? Predict, then look:

$ javac *.java

$ java Startup
reading ada@example.com.txt
reading bob@example.com.txt
started
[ada@example.com: hello, bob@example.com: hi ada]
[ada@example.com: hello, bob@example.com: hi ada]

Both files were read before anyone asked for either book. Bob's was read for nobody. With two users, that costs little. With a thousand, every start of the server reads a thousand files, whether or not their users ever ask.

We want a book whose file is read when someone first asks for it. And Startup and every handler should stay as they are, since each of them holds a Book.

A stand-in for the book

Here is LazyBook, whole:

LazyBook.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
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
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

/** The book saved in a file, read only when it is first used. */
class LazyBook implements Book {
    private final Path file;
    private SavedBook real = null;
    // AF(this) = the book saved in file. real is that book, once it
    //     has been read, and null until then.

    /** @effects makes the book saved in file, reading nothing yet */
    public LazyBook(Path file) {
        this.file = file;
    }

    /** @return the book saved in file, reading it if it is not read */
    private SavedBook real() throws IOException {
        if (real == null) {
            real = new SavedBook(file);
        }
        return real;
    }

    @Override
    public void add(User asker, String message) throws IOException {
        real().add(asker, message);
    }

    @Override
    public List<String> messages() throws IOException {
        return real().messages();
    }
}

The private method real() makes the SavedBook the first time it is called, on lines 19 to 21, and returns that same one every time after. add and messages each forward the call to real(). So LazyBook stands in for a SavedBook. It is a wrapper: a field holding the object, and calls forwarded to it. Unlike a decorator, it adds nothing to what a call does. What it changes is when the SavedBook is made.

Now change line 18 of Books to books.put(login, new LazyBook(file));. No other line changes. Ada asks for her book again. Which files are read now?

$ javac *.java

$ java Startup
started
reading ada@example.com.txt
[ada@example.com: hello, bob@example.com: hi ada]
[ada@example.com: hello, bob@example.com: hi ada]

Only ada's file was read, at her first request. Her second read nothing, since real already held her book. Startup gets a Book from bookOf, so nothing in it can tell which class it has.

Definition: proxy

A proxy is a wrapper that has the interface of the object it wraps and controls access to that object.

"The interface of the object" is why Startup did not change. "Controls access" is the proxy's job. LazyBook controls when the object is made, and a proxy of another kind could control whether a call reaches the object at all. Such a proxy has the shape of a decorator that takes behavior away, as unmodifiableList does: the two differ in what the wrapper is for, not in how it is built. Design Patterns gives the pattern's intent as "a surrogate or placeholder for another object to control access to it."11 Its motivating example is a virtual proxy like LazyBook: a document editor's proxy for a large image keeps the image's file name, and reads the file only when the image is drawn.

What javac checks about a proxy

SavedBook's messages throws nothing. So why does Book's, on line 14, say it may throw an IOException? Take the clause out, so that line 14 reads List<String> messages();, with Books making LazyBooks:

$ javac *.java
LazyBook.java:31: error: messages() in LazyBook cannot implement messages() in Book
    public List<String> messages() throws IOException {
                        ^
  overridden method does not throw IOException
1 error

LazyBook's messages calls real(), which may read the file, and reading a file can fail. When we studied subtyping, each checked exception an override declares had to be "one that the overridden method declares, or a subclass of one." A method that implements an interface's method is held to the same rule.12 So javac checks each of a proxy's methods against the interface's: its name, its types, and the checked exceptions it may throw. The cost falls on clients: each call of messages through a Book has to catch IOException or declare it, even when the book is a SavedBook. And a file that cannot be read now fails at a user's first request, not at the server's start.

A copy of LazyBook whose line 32 asks the field, return real.messages();, still compiles, since the field and the method are both a SavedBook, but the field is still null at ada's first request, and the copy throws a NullPointerException. javac checks nothing about the forwarding: that each method goes through real(), that a file once read is not read again, or that LazyBook satisfies Book's specification. We know those by reading LazyBook. Its fields are private. real starts null, on line 8, and only line 20 assigns it. And each method's body is one call of real().

The pattern. In the same four parts:

  • Name: proxy. LazyBook is a virtual proxy.
  • Problem: control access to an object, such as when it is made.
  • Solution: a stand-in that has the object's interface, and forwards each call to it.
  • Gains: only Books changes, and a file is read only if it is used.
  • Costs: a forwarding method for each method, which javac does not check; the throws clause on Book's methods; and a read can fail later, at a request.

When is the trade worth it? A virtual proxy fits when making the object is slow and many objects are never used, as with a thousand books. With two users, Books making SavedBooks is simpler, and a file that cannot be read stops the server at its start, where whoever started it sees the error.

Design Patterns names other kinds of proxy. A remote proxy stands in for an object in another address space, such as on another machine. A protection proxy checks that the caller may make the call. The guestbook needs no protection proxy. In Lecture 19, Book's delete already refuses a user who is not the book's owner, so a wrapper that checked the owner again would add nothing. And with the check only in a proxy, the argument that only owners delete would also need to know that no client ever holds the Book the proxy wraps.

Today's patterns

Lecture 20 judged each pattern by what javac checks. Here is each of this lecture's, with what a reader or a test establishes in its place:

  • Interning: javac checks nothing. == compiles whether or not two objects are shared. Integer.valueOf's promise covers only -128 to 127, so a client compares values with equals.
  • Builder: javac checks each part's method name and type. It does not check that every part is set, which build() checks at run time, or that each value goes to the right part. A reader can see author(owner).
  • Adapter, decorator, and proxy, the wrappers: javac checks that the wrapper has the interface's methods, with their types and no checked exception beyond the interface's. It does not check that the wrapper satisfies the specification: DequeQueue without its check, LoggingQueue without line 16, and LazyBook calling real.messages() each compiled.
  • Composition in place of subclassing: javac refuses a subclass of OfficeQueue and accepts a wrapper of its one object. It never checks whether ListQueue's methods call one another.

With this lecture, this course's creational and structural patterns are done. The behavioral kind comes in Design Patterns 3, on Wednesday, December 2.

Exercises

Each answer is folded under its question. Write yours first.

1. A teammate writes this method, with a precondition that neither argument is null:

static boolean same(Integer a, Integer b) returns whether a and b stand for the same number.

Its body is return a == b;. A test calls same(Integer.valueOf(100), Integer.valueOf(100)), expects true, and passes. Do we know that same works? If not, which calls could go wrong, and what is the fix?

Answer
  • No: the test confirms only its own run. The test is line 5 of Sharing again. For 100, Integer's documentation promises one shared object, so a == b is true, and the test passes.
  • A number outside -128 to 127 could go wrong. For same(Integer.valueOf(1000), Integer.valueOf(1000)), the documentation allows the two calls to return two objects. Then a == b is false, though the two stand for the same number, and same returns false where its specification asks for true. A test with such a number is the one that could refute same. Even if it passes, it confirms only its own run, on one JDK.
  • The fix is return a.equals(b);. Integer's documentation promises that its equals is true exactly when the argument is an Integer holding the same int. That promise covers every number, shared or not, so we can argue that same satisfies its specification without running it. (The precondition matters here: a.equals(b) throws if a is null.)

2. Bloch's builder takes the parts an object must have as arguments to the builder's constructor. It gives a named method only to each optional part, one the object may go without. Every part of a Message is one it must have. Rewrite Message.Builder in Bloch's form, and write the call that signs ada's book. Which mistakes does javac catch now: a part left out, a swap? When is Bloch's form the better one?

Answer
  • The builder's constructor takes all three parts. No setter is left, and build() only makes the message, since the constructor's @requires asks the client for parts that are not null:

    answers/Message.java
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    /** The parts of a message, all given to the constructor. */
    public static class Builder {
        private final String author;
        private final String owner;
        private final String text;
    
        /**
         * @requires author, owner, and text are not null
         * @effects makes a builder for the message text, by author,
         *     in owner's book
         */
        public Builder(String author, String owner, String text) {
            this.author = author;
            this.owner = owner;
            this.text = text;
        }
    
        /** @return the message with the parts given */
        public Message build() {
            return new Message(this);
        }
    }
    
  • The call is the positional constructor's again. It reads new Message.Builder(asker, owner, "hi ada").build(). So javac once more refuses a part left out: the argument lists differ in length. It accepts a swap, which is as hard to see as with the constructor. answers/Signing.java makes the call right, then swapped:

    $ java Signing
    bob@example.com signs ada@example.com's book: hi ada
    ada@example.com signs bob@example.com's book: hi ada
    
  • Bloch's form pays when parts are optional. Then the required parts go by position, where javac counts them. Each optional part gets a named method, which a client calls or leaves out. With no optional part, Bloch's form is the constructor with a second class around it.

3. A TA would rather a second join of a student did nothing than throw, and writes a decorator, QuietQueue. Its field and constructor are like LoggingQueue's, and its size, next, and waiting only forward. Its join is:

QuietQueue.java
15
16
17
18
19
    public void join(String netid) {
        if (!inner.waiting().contains(netid)) {
            inner.join(netid);
        }
    }

Does javac accept QuietQueue? Does QuietQueue satisfy HelpQueue's specification? If line 5 of HelpQueues returns new QuietQueue(new ListQueue()), what does Twice print?

Answer
  • javac accepts it. QuietQueue has HelpQueue's four methods, with their types, and inner has waiting and join.

  • QuietQueue does not satisfy HelpQueue's specification. join's @throws clause promises an IllegalArgumentException if the student is already in the queue. QuietQueue's join returns normally then.

  • Twice prints one line. The second join throws nothing, so Twice's catch never runs:

    $ java Twice
    [ada]
    

    The queue holds ada once, as it should. But the second join reports nothing, so a client that tells ada she is already waiting, as Twice's line 9 does, never runs that line.

  • So QuietQueue breaks Lecture 14's rule. It says implements HelpQueue, so it is a Java subtype of HelpQueue. But its join breaks a promise of HelpQueue's join, so it is not a behavioral subtype. A decorator may change what an object does only where the specification says nothing, as it says nothing about printing. The TA's wish needs a different specification, and so a different interface.

4. In a copy of LazyBook, real() makes a new SavedBook on every call:

    private SavedBook real() throws IOException {
        real = new SavedBook(file);
        return real;
    }

With Books making LazyBooks, does javac accept the copy? What does java Startup print? And does the copy satisfy Book's specification?

Answer
  • javac accepts the copy. real() still returns a SavedBook and declares IOException, so every type agrees.

  • Ada's file is read at each request. Here is the run:

    $ javac *.java
    
    $ java Startup
    started
    reading ada@example.com.txt
    [ada@example.com: hello, bob@example.com: hi ada]
    reading ada@example.com.txt
    [ada@example.com: hello, bob@example.com: hi ada]
    
  • The copy satisfies Book's specification, if nothing else writes the book's file. Each call of add or messages makes a new SavedBook, which reads the file anew. add then adds the message and writes the whole list back to the file. So the file holds every message posted, oldest first, and messages returns exactly those.

  • It loses the proxy's gain. Book's specification says nothing about when, or how often, a file is read. So neither javac nor an argument from the specification can catch the copy. A run that shows each read, as line 17 of SavedBook does, catches it. The promise to read once is written only in LazyBook's own comments, such as its class's "read only when it is first used", and the copy breaks it.

5. Here again is LoggingListQueue, with LoggingQueue's next:

LoggingListQueue.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
/** A ListQueue that prints a line for each join and next: a subclass. */
public class LoggingListQueue extends ListQueue {
    @Override
    public void join(String netid) {
        super.join(netid);
        System.out.println("log: join " + netid);
    }

    @Override
    public String next() {
        String netid = super.next();
        System.out.println("log: next " + netid);
        return netid;
    }
}
LoggingQueue.java
20
21
22
23
24
public String next() {
    String netid = inner.next();
    System.out.println("log: next " + netid);
    return netid;
}

For each claim, say whether javac checks it. If it does not, say how you would know it instead.

  1. LoggingListQueue's join overrides a join of ListQueue.
  2. LoggingQueue's next returns the NetID the inner queue removed.
  3. LoggingListQueue satisfies HelpQueue's specification.
Answer
  • javac checks claim 1, because of line 3. @Override asks it to check that ListQueue has a join(String).
  • javac does not check claim 2. It checks only that next returns a String. A reader sees that line 23 returns netid, the value line 21 got from inner.
  • javac does not check claim 3. The argument reads the code. Each override calls ListQueue's method first, so a join that ListQueue refuses throws before the print, and leaves the queue unchanged. The print changes no queue. size and waiting are ListQueue's own. So LoggingListQueue satisfies the specification if ListQueue does. A later ListQueue whose method calls join can still make the log wrong: with joinAll, LoggingListQueue logged each student twice. That extra line breaks no promise of HelpQueue. It breaks LoggingListQueue's own comment, a line for each join.

Further reading

  • The catalog. Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software (1995): Builder on page 97, Adapter on 139, Decorator on 175, and Proxy on 207.
  • The patterns in Java. Joshua Bloch, Effective Java, 3rd edition (2018). Item 1 is the static factory method, Item 2 the builder, and Item 18, "Favor composition over inheritance", the comparison of a wrapper with a subclass.

  1. Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software (1995), chapter 1. Chapters 3, 4, and 5 hold the creational, structural, and behavioral patterns. ↩

  2. Joshua Bloch, Effective Java, 3rd edition (2018), Item 1, the second advantage of a static factory method, with Boolean.valueOf as its example. Bloch calls this sharing "similar to the Flyweight pattern" (page 6), which Design Patterns files among its structural patterns. ↩

  3. Oracle, Java SE 25 API Specification (2025), the documentation of Boolean.valueOf(boolean), Integer.valueOf(int), and String.intern(), for lines 4, 5, and 7. ↩

  4. Bloch, Effective Java, Item 2, pages 10 to 16. The swapped parameters are on page 11, the JavaBeans pattern on pages 11 and 12, and the suggestion of four or more parameters on page 16. ↩

  5. Gamma, Helm, Johnson, and Vlissides, Design Patterns (1995): Adapter, page 139, which gives both the class adapter and the object adapter; Decorator, page 175; and Proxy, page 207. ↩↩↩

  6. Bloch, Effective Java, Item 18, uses the same two words, and keeps "delegation" for a wrapper that passes itself to the object it wraps (page 91). ↩

  7. Oracle, Java SE 25 API Specification (2025), the documentation of the class java.util.ArrayDeque, at https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/ArrayDeque.html. The new list on line 26 lists the elements in the order the ArrayDeque hands them out, as the documentation of the constructor ArrayList(Collection) says. ↩

  8. Oracle, Java SE 25 API Specification (2025), the documentation of the method java.util.Collections.unmodifiableList, at https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Collections.html#unmodifiableList(java.util.List). ↩

  9. The Java Language Specification, Java SE 25 edition, section 8.8.9: the default constructor "invokes the superclass constructor with no arguments". ↩

  10. Bloch, Effective Java, Item 18, pages 87 to 89. ↩↩

  11. Gamma, Helm, Johnson, and Vlissides, Design Patterns (1995), Proxy, page 207, which also gives the image example and the remote, virtual, and protection kinds. ↩

  12. The Java Language Specification, Java SE 25 edition, section 8.4.8.3, whose rule covers "methods that implement abstract methods defined in interfaces". ↩