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.

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. 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. 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.

Contact information

(+32) 496 38 00 82

infonull@nullprincipal-itnull.be