The Builder Pattern

Nat Pryce has a good blog post on using the Builder pattern.

I especially like the result:

"Another benefit is that the test code is easier to write and read because the parameters are clearly identified. Compare:"

TestAddresses.newAddress( "Sherlock Holmes", "222b Baker Street", "London", "NW1"); to: new AddressBuilder() .withName("Sherlock Holmes") .withStreet("222b Baker Street") .withCity("London") .withPostCode("NW1", "3RX") .build();

I hope to find some opportunities to use this in the code I write.  This is the type of syntax I really like in the NHibernate ICriteria queries that are built.

Update: the correct term is ‘fluent interfaces’ – here is another example from the Eleutian SpeakENG blog on ‘Fluent Fixtures’

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s