DSLs and extension methods

I ran across this presentation on building library APIs that feel like a domain specific language. An example from his slides:

calendar.add("dentist").from(fourPM).to(fivePM).at("123 main street") ;

The method calls look like an English sentence. In fact, this looks at lot like LINQ’s API style. With extension methods, one can add these methods to any existing class to make a more readable API. Read on for some code to implement 4.Hours().FromNow() and 2.Hours().Ago() using extension methods. Someone could add an entire vocabulary for simple transformations on time.

static class TimeHelpers    {
     public static TimeSpan Hours(this int i) {return TimeSpan.FromHours(i);}
     public static DateTime FromNow(this TimeSpan t) {return DateTime.Now.Add(t);}
     public static DateTime Ago(this TimeSpan t) {return DateTime.Now.Subtract(t);}
}
Advertisements

2 comments

  1. Pingback: Fluent Interfaces with ‘with’ « Handwaving

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