Blog

Generic Expression Builder

July 25, 2009

I blogged about fluent interfaces and expression builders a couple of times before. For this post, I want to share a base class that I've been using for taking away some of the burden when creating expression builders for domain classes.

Here's the expression I'm after:

This creates an instance of a domain class named Document with the name of the author, its title and with an associated tag. Let me first show the code of the expression builders that make this happen.

The expression builders all provide progressive interfaces. Also notice that the DocumentBuilder derives from a base class named Builder. This class provides a method ProvideValueFor that is used to feed the base class with the name of a property and a corresponding value. Collections are also supported. Here's the code for the Builder class.

var document = DocumentBuilder.BuildDocument()
    .AuthoredBy("Stephen Hawking")
    .Titled("The Universe in a Nutshell")
    .TaggedWith(tag => tag.Named("Physics"))
    .Build();

Using this approach, its no longer necessary to make any compromise of exposing property setters or a dedicated constructor just for serving the expression builders. The Builder class uses refection to set the value of a property or to fill a collection. The BackingFieldResolver is a class I picked up from this post. Very cool stuff!

I have only used this approach in a couple of side projects, but let me know you think.

Till next time.

If you're interested in an in-person or online course that teaches you and your team how to write maintainable unit tests and get the most out of TDD practices, make sure to have a look at our trainings and workshops or contact us at infonull@nullprincipal-itnull.be.

Profile picture of Jan Van Ryswyck

Jan Van Ryswyck

Thank you for visiting my blog. I’m a professional software developer since Y2K. A blogger since Y2K+5. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Comments

About

Thank you for visiting my website. I’m a professional software developer since Y2K. A blogger since Y2K+5. Provider of training and coaching in XP practices. Curator of the Awesome Talks list. Past organizer of the European Virtual ALT.NET meetings. Thinking and learning about all kinds of technologies since forever.

Latest articles





Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be