InfoQ

News

Extension Methods, DSLs, and Fluent Interface

Posted by Jonathan Allen on Nov 23, 2007 06:12 AM

Community
.NET
Topics
Domain Specific Languages
Tags
Orcas,
Visual Basic.NET,
C#

What is the difference between an Internal DSL and an API? Martin Fowler described an internal DSL back in February of 2004 as,

The lisp and smalltalk communities also have a strong tradition of DSLs, but they tend to do it another way. Rather than define a new language, they morph the general purpose language into the DSL. (Paul Graham describes this well in Programming Bottom-Up.) This Internal DSL (also referred to as an embedded DSL) uses the constructs of the programming language itself to define to DSL. This is a common way to work in any language, I've always thought of defining functions in such a way to provide a form of DSL for my problem. But lispers and smalltalkers often take this much further. Another term for an API written in this style is FluentInterface.

Two and a half years later he says,

For internal DSLs, the fuzzy boundary is what is an API and what is a DSL. Fundamentally there is no difference, an internal DSL is just an API with a fancy name (as the old Bell labs saying goes: "library design is language design"). Despite this, however, I think there is a different feel when you are working with an API that's written with a DSL feel. Things like a FluentInterface can make working with an API a qualitatively different experience. Thinking in DSL terms makes you think about readability in a different way, exploiting the syntax of the host language to create something that seems to stand on its own - rake is a great example of this.

So what exactly does an Internal DSL look like? Usually the answer comes back as an example of fluent programming. In fluent programming, all methods return either the same object or a new object. This allows method calls to be chained together.

For an example, we turn to an excerpt from Neal Ford's QCon presentation "Building DSL's in Static and Dynamic Languages".

def c = 2.days.fromToday.at(4.pm)

Until recently hacking interstice classes like integer required a dynamic language like Ruby or Python, specifically because they provide something called "open classes". An open class allows one to add new methods to a class at runtime.

So what does this have to do with a .NET developer using C# or VB? Well, C# 3 and VB 9 both support something called Extension Methods. Extension methods allow users to statically add methods to a pre-existing class. You could for example create a "days" method that takes an integer and returns a TimeSpan.

Consider the difference between this C# 2.0 code and the same thing written in C# 3.0.

//C# 2.0
date d = Helper.At(Helper.FromToday(Helper.Days(2)), Helper.Pm(4));
//C# 3.0
date d = 2.Days().FromToday().At(4.Pm);

It should be noted that these two lines of code compile to exactly the same thing. All the heavy lifting was done by the compiler and the Extension attribute.

A final tip for using extension methods. Though officially supported only in .NET 3.5, Jared Parsons found a way to use extension methods in .NET 2.0. Basically it comes down to creating a fake "ExtensionAttribute" class that the new compilers confuse for the real one.

5 comments

Reply

  1. Back to top

    I guess they could have done it better

    Nov 23, 2007 4:34 PM by Sadek Drobi

    I am one of the biggest fans of c# 3.0 features. Yet I guess that there are things that could have been done better. One of them is this "Extension Methods" story. First of all thank you for gently pointing out that both the above lines of code compile to the same thing, but who else will? In ruby case, code still belongs to the object, even when we reopen classes, we add methods to that same object. That means we are keeping our modularity. We should be very careful using extension methods. I guess C# team chose the easiest solution, which is to implement such a specific feature. And worse to overload the "." to handle two different things! Yes, two completely different things. I guess it won’t be less fluent to use the "#" character, or any other that shows the difference. Well even better, to allow an open compiler, and to add a macro mechanism for such a syntactic sugar. Because it, as they like to say, all is about syntactic sugar...

  2. Back to top

    Wrong .NET 3.5 sytanx

    Nov 23, 2007 8:09 PM by Seth Yuan

    Extension methods means to methods, not properties. So I think you forgot to put parenthesis around those method calls.

  3. Back to top

    Re: Wrong .NET 3.5 sytanx

    Nov 25, 2007 3:32 AM by Jonathan Allen

    Yep, you caught me. I have to admit I do so much VB programming I forget that C# requires empty parenthesis sprinkled all over the place.

  4. Back to top

    Fuzzy Border

    Nov 27, 2007 12:14 AM by Phillip Calçado

    Sating the differences (if any) between DSLs and Fluent Interfaces is a very hard thng. I have some points here: http://fragmental.tw/research-on-dsls/language-adaption/

  5. Back to top

    Re: Fuzzy Border

    Jun 30, 2008 5:12 PM by berkay NiQuiL

Exclusive Content

Rationalizing the Presentation Tier

Thin client paradigm characterized by web applications is a kludge that needs to be repudiated. Old compromises are no longer needed and it's time to move the presentation tier to where it belongs.

Agile Project Management: Lessons Learned at Google

In this presentation filmed during QCon 2007, Jeff Sutherland, the creator of Scrum, talks about his visit at Google to do an analysis of Google's first implementation of Scrum.

AtomServer – The Power of Publishing for Data Distribution

In this article, Bryon Jacob and Chris Berry introduce AtomServer, their implementation of a full-fledged Atom Store based on Apache Abdera, which is now available as open source.

An Introduction to Virtualization

It is easy to think that virtualization applies only to servers. In reality the recent resurgence of the concept is also being applied to networking, storage, and application infrastructure.

REST Anti-Patterns

In this article, Stefan Tilkov explains some of the most common anti-patterns found in applications that claim to follow a "RESTful" design and suggests ways to avoid them.

Choosing between Routing and Orchestration in an ESB

In this article, Adrien Louis and Marc Dutoo discuss the differences and relative merits of using orchestration vs. routing in a typical ESB setup, and discuss various implementation options.

Enterprise Batch Processing with Spring

Wayne Lund discusses batch processing, Spring Batch objectives and features, scenarios for usage, Spring Batch architecture, scaling, example code, failures and retrying, and the future roadmap.

User Story Estimation Techniques

Developer Jay Fields draws on his experiences as a ThoughtWorks consultant to describe effective user story estimation techniques.