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);}
}
January 12, 2008 at 12:59 am |
I’m inspired by your post!
I’ve created a cool little sample using generic extension methods to describe a date of birth. Read more; http://www.develop-one.net/blog/Trackback.aspx?guid=ed33760f-43f5-4b3c-9c75-c5ff84ac14f4
Cheers,
Mark