I have been reading Effective Java by Joshua Bloch and learned something new so I wanted to try it out.

Making long parameter lists in your constructor is not fun and prone to errors. Previously I thought that best way to handle this situation was to make a bunch of setter methods. This can get kind of tedious and hard to follow when there are alot of parameters:

JAVA:
  1. Address myaddress = new Address("Chicago", "IL");
  2. myaddress.setZip("44422");

Using a Builder object:

JAVA:
  1. Address myaddress = new Address.Builder().city("Chicago").state("IL").zip("44422").build();

Using a builder class allows you to specify params in any order too!

Here is the source code for my Address class with Builder. The builder is implemented as a nested class since it will only be used by the Address class.

Address class with Builder

Test for Address class

The required parameters are set in the Builder constructor:

JAVA:
  1. public void testBuilderDefaults() {
  2. Address expected = new Address.Builder("Chicago", "IL").build();
  3. assertEquals("State is IL", "IL", expected.getState());
  4. assertEquals("City is Chicago", "Chicago", expected.getCity());
  5. }

then the optional params are chained to that:

JAVA:
  1. public void testBuilderStreetStateZip() {
  2.   Address expected = new Address.Builder("Chicago", "IL").street("this is an address").zip("11111").build();
  3. assertEquals("Address is this is an address", "this is an address", expected.getStreet());
  4. assertEquals("Zip is 11111", "11111", expected.getZip());
  5. assertEquals("State is IL", "IL", expected.getState());
  6. assertEquals("City is Chicago", "Chicago", expected.getCity());
  7. }

The book goes into more discussion that I haven't quite wrapped my head around yet, but this is interesting stuff .. even though it is java ;)