The Java Specialists' Newsletter
Issue 1122005-08-22 Category: Book Review Java version: Sun JDK 5.0
Subscribe RSS Feed

Book Review: Head First Design Patterns
by Dr. Heinz M. Kabutz
This book is a fantastic introduction to Design Patterns, probably the best available. In this newsletter, I look at some of the winning formulae used in the book, and explain why they work. I also give some tips of where I disagree with the book and some additional information that will be useful to you.

Welcome to the 112th edition of The Java(tm) Specialists' Newsletter. Helene flew to Durban for a few days so I had the pleasure of being "mom" to our kids Maxi (7) and Connie (3). We had a great time together. Besides being "mom's taxi", we also took the opportunity to drive to Hermanus, a small ex-whaling town about an hour drive, where we saw 10 Southern Right Whales. My camera does not zoom well, and I preferred enjoying the view to taking pictures, but here is a lucky shot of a whale blowing his spout. We saw some tails stuck in the air and a bit of breaching, but I did not capture any of those on camera. Do send me an email if you intend visiting Cape Town, and time permitting, I will show you around Hermanus :)

Some feedback re my plan to get Java programmers involved in the fight against HIV/AIDS, as mentioned last month. After interviewing several people who are working amongst those affected by HIV/AIDS, I have sadly concluded that there is little to nothing we can do to help.

NEW: Refactoring to Java 8 Lambdas and Streams Workshop Are you currently using Java 6 or 7 and would like to see how Java 8 can improve your code base? Are you tired of courses that teach you a whole bunch of techniques that you cannot apply in your world? Check out our one day intensive Refactoring to Java 8 Lambdas and Streams Workshop.

Book Review: Head First Design Patterns

In my newsletter, I have mentioned my seminar on Design Patterns several times. Over the years, hundreds of Java and C++ programmers have attended and have enhanced their way of thinking regarding OO.

There are several techniques that I use to make sure that people learn:

  1. Funny pictures: To keep our mind working optimally, we need to regularly have our attention focused with little pictures. I use a professional book illustrator with a wicked sense of humour to draw them for me. Have a look at her rendition of the Data Access Pattern. The guy at the top is the business object, who does not care where the data comes from, and the small guy on the staircase is the data access object.
  2. Short stories: Our brain cannot operate at 100% all of the time. It needs many short breaks, in the form of relevant jokes and funny stories to give us a break from thinking for a minute. Afterwards, everyone is refreshed, and we can get far more information transferred.
  3. Practical exercises: A large portion of the course is spent solving design exercises. You learn by doing, not by hearing.

I still believe that my course is the quickest way in which a programmer can learn to think Object Orientated. My course is cheap (I was told this by two of my most recent customers). The best price works out at only EUR 185 per person per day of training (conditions apply). However, this is still out of reach for quite a large number of software companies.

So, what should you do, if your company cannot afford EUR 185 per day for you to be trained in Design Patterns? There is a very good alternative, the book Head First Design Patterns, which will cost you about USD 30 from A lot cheaper than any seminar! And if you share the book, 20 people could learn from one book, which works out to USD 1.50 per developer.

"Head First" is a new series of books by O'Reilly. When I opened the predecessor book "Head First Java", I knew O'Reilly had produced a winner. They were using the techniques that worked so effectively in my own courses:

    1. Funny pictures: Not just the front covers of these "Head First" books are hilarious, but the rest of the books is filled with funny pictures and captions. How many Java books do you know that feature a pretty girl on the front cover?
    2. Short stories: The books do not have anecdotes, but the examples are very entertaining.
    3. Practical exercises: Interspersed through the chapters are exercises together with model solutions. These exercises force you to review the chapter and this helps to solidify the learning.

Since the original Design Patterns - Erich Gamma et al (GoF Book), I have been waiting for a book like this, that agrees with my interpretation of GoF and contains well-implemented examples. On the front cover, there is the statement: "Learn why everything your friends know about Factory pattern is probably wrong". This is so true! Martin Fowler, in Refactoring, used the name Factory Method for a static method that constructs objects. When I asked him about that, he admitted that it was quite different to the GoF Factory Method, and wondered why none of his reviewers had picked that up!

My course goes into a lot more depth than the book does, especially during our exercise and discussion times, but for a book, their interpretation of GoF is spectacular. There are a few places where they missed some points, so if you read the book, add these points, and you will pretty much get my course for only USD 30!

  • Difference between Decorator, Adapter and Proxy: The intents are different, but the structure is almost the same, as you can see in the interviews between the patterns. Something they did not point out is where the client points to. In Adapter and Proxy, the client object has a pointer to the top-level interface, in Decorator to the bottom classes, the "decorators".
  • Composition vs Aggregation vs Association: This used to be an important consideration with C++ memory management, but in Java does not matter anymore. I agree to stick to one term, such as Composition, even though, strictly speaking, you only have association in Java.
  • Command Pattern: Something they did not point out is what happens when exceptions occur in the execute() method, or if you want to return a result from a command. The decoupling of the Command pattern works against you in this case. Have a look java.util.concurrent.Callable and java.util.concurrent.Future to see how a command pattern could return results to the client.
  • Class Adapter: In the book, they claim that this is of no use in Java, because you do not have multiple inheritance. This statement is not entirely correct. If your target is an interface, then there is nothing stopping you from implementing the interface and extending another class. That was the only serious error I found in the book.
  • Singleton: In this chapter, the authors did a fantastic job of explaining how a Singleton should be initialised, including the argument about double-checked locking. However, they omitted to mention the biggest reason for using a Singleton rather than static methods, in that you can override the Singleton with a subclass, as is done in java.awt.Toolkit.
  • Iterator: I also mention the special case of the NullIterator. This is an instance of an Iterator that is always empty. Because you only ever need one of these, you should make it a Singleton object. In addition, it should mimic the behaviour of an empty collection. See below for my implementation of NullIterator.
  • Facade: The Facade pattern is in my opinion not really a design pattern, since you cannot draw a typical class diagram structure of it. It is necessary, however, because when you use Design Patterns, you end up with flexibility, and lots of classes. The Facade pattern is meant to make things more manageable. As an example, look at java.util.concurrent.Executors.

What I found interesting was the book's choice of patterns and the examples that they showed were almost identical to mine. We could not have copied from one another, since I wrote my examples long before the book, and my course material is not publicly available. Reading this book is like hearing myself talk, which might explain my enthusiasm for it.

Here are the patterns that I cover: Adapter, Command, Composite, Decorator, Factory Method, Façade, Flyweight, Iterator, Proxy, Singleton, State and Strategy.

And here are the patterns covered in the book: Abstract Factory, Adapter, Command, Composite, Decorator, Factory Method, Façade, Iterator, Observer, Proxy, Singleton, State, Strategy and Template Method.

Almost identical!

I left out Observer and Template Method because they were too simple and the Abstract Factory because I have not used that myself. And I included the Flyweight because it is a performance tuning pattern. In addition, I also added a few J2EE patterns (not listed above).

Another "nice touch" of the book was to teach OO Principles, one at a time:

  • Encapsulate what varies
  • Favour composition over inheritance
  • Program to interfaces, not implementation
  • Strive for loosely coupled designs between objects that interact
  • Classes should be open for extension but closed for modification
  • Depend on abstractions. Do not depend on concrete classes.
  • Only talk to your friends
  • Don't call us, we'll call you
  • A class should have only one reason to change

This book is probably not advanced enough if you are already actively working with patterns. If that is you, I would rather recommend Design Patterns Explained, which in my opinion goes into more depth for the patterns.

Null Iterator

The idea of the Null Iterator comes from the GoF book, and is similar to the Null Object Pattern by Bobby Woolf. I don't know if that link is the best, if in doubt, buy the PLoPD3 book. That book is a bit dated though, beware.

Here is an implementation of the NullIterator, according to Kabutz ;-) It is more correct than the one in the book, in that mine throws the exceptions you would expect from a normal empty list. Note that I am suppressing the unchecked warnings using the new annotation @SuppressWarnings. This annotation does not seem to be implemented in the Sun javac compiler, but both IntelliJ IDEA 5.0 and Eclipse 3.1 support it.

import java.util.*;

public class NullIterator implements Iterator {
  private static final Iterator iterator = new NullIterator();
  // since we cannot get any objects with next(),
  // we can safely cast it to your type, so we can
  // suppress the warnings
  public static <T> Iterator<T> getIterator() {
    return iterator;
  private NullIterator() {}
  // always empty!
  public boolean hasNext() {
    return false;
  // Empty collections would throw NoSuchElementException
  public Object next() {
    throw new NoSuchElementException("Null Iterator");
  // Should only be called after a next() has been called.
  // Since next() can never be called, the correct exception
  // to throw is the IllegalStateException.
  public void remove() {
    throw new IllegalStateException("Null Iterator");

So, if a method needs to indicate that it contains no elements, such as if you want to iterate over the leaves in a Composite pattern, you can simply return the NullIterator instance. This makes the client code easier, since you do not need to test for null anymore.

The Null Object Pattern is a special case of the Strategy pattern and can be used in most places where you are testing for whether a field or method return value are null.

That's all for this newsletter, I look forward to your comments as always :)

Kind regards


P.S. Yes, I do get a tiny commission if you buy the book through the Amazon link that is included in this email. In my experience with other book reviews, only about 5 readers end up buying the book through the link, so it costs me far more to send you this email than I would ever make through referral fees. I am not reviewing that book for the referral fees, but because I feel it is a great book to own.

Book Review Articles Related Java Course

Would you like to receive our monthly Java newsletter, with lots of interesting tips and tricks that will make you a better Java programmer?