InfoQ

InfoQ

News

My Bookmarks

Login or Register to enable bookmarks for unlimited time.

The content has been bookmarked!

There was an error bookmarking this content! Please retry.

Extension Methods, DSLs, and Fluent Interface

Posted by Jonathan Allen on Nov 23, 2007

Sections
Development,
Architecture & Design
Topics
.NET ,
Domain Specific Languages
Tags
Visual Basic.NET ,
Orcas ,
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.

I guess they could have done it better by Sadek Drobi Posted
Wrong .NET 3.5 sytanx by Yuan Seth Posted
Re: Wrong .NET 3.5 sytanx by Jonathan Allen Posted
Fuzzy Border by Phillip Calçado Posted
  1. Back to top

    I guess they could have done it better

    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

    by Yuan Seth

    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

    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

    by Phillip Calçado

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

Educational Content

New-age Transactional Systems - Not Your Grandpa's OLTP

John Hugg discusses high volume transaction processing applications with high and low frequency profiles, and how VoltDB can be used for that purpose.

Cool Code

Kevlin Henney examines code samples to see what can be learned from them starting from the premise that one won’t write great code unless he knows how to read it.

Collaboration: At the Extremities of Extreme

Jason Ayers share the observations he made watching a team of developers collaborating in real time on the same code base, pushing XP, pair programming and continuous integration to their extremes.

Yesod Web Framework

Michael Snoyman presents Yesod, a web framework written in Haskell and containing a web server, templating, ORM, libraries (templating, gravatar, etc.).

Transactions without Transactions

Richard Kreuter and Kyle Banker on how to avoid classical RDBMS transactional systems by using compensation mechanisms, transactional messaging or transactional procedures.

Attila Szegedi on JVM and GC Performance Tuning at Twitter

Attila Szegedi talks about performance tuning Java and Scala programs at Twitter: how to approach GC problems, the importance of asynchronous I/O, when to use MySQL/Cassandra/Redis, and much more.

10 tips on how to prevent business value risk

One category of risk that project teams need to ensure they address is business value failure – delivering a product that fails to provide value for the business investor.

Interview: Software Systems Architecture: Working With Stakeholders Using Viewpoints and Perspectives

InfoQ spoke to the authors of Software Systems Architecture on a couple of new topics, the System Context viewpoint and Agile, which have been added to the second edition.