Saturday, November 8, 2008

RubyConf 2008 Day 3 - Advanced DSL's in Ruby

Neal Ford gave this talk and I would say that this was one of the best presentations at this conference. For the most part Neil is talking about some of the patterns that Fowler has been working on in his book only using examples written in Ruby. Ford also introduces some patterns he has identified and a handful of interesting frameworks to help support writing both internal and external DSLs.

The Beginning

He started by discussing the fluent interfaces, which use method chaining to express logic in a "sentence". The challenge with using this style is how method chaining semantics requires "an explicit terminator ", but that causes a "the finishing problem" because it breaks the fluency in the language. In order to mitigate this problem he advised the audience to use a wrapper context and use nested methods to control completion: e.g. rules.add(Discount.new.based_on(foo)) instead of rules.add_discount_based_on(foo)

The Middle

Another thing to keep in mind is that we should control the context. In other words, alias methods so that it reads a little better: e.g. Instead of recepie.instance_eval { @ingredients } alias instance_eval to provide context recepie.consists_of{ @ingredients }
He goes on to discuss a few more ways to combat the finishing a.k.a. stopping problem. A common mistake he sees people make in Ruby is using method_missing as a factory to create types. This approach violates the open-closed principle so he advised the audience to use Mixins and builders instead of using method_missing.

Almost at the End

Some other interesting things he discussed where function sequences, bubble words i.e. words that are there for readability not and executable statement, and the declarative nature of DSLs.
Sprinkled throughout the presentation were examples of some DSL code in Ruby. What I found particularly interesting was the work that Jay Fields has done with Business Natural Languages.
Just remember the three P's (Polish, Preprocess, Parse):
Polish => simple string substitutions to convert nearly ruby to actual ruby
Pre-process => load strings and modify to coerce them into ruby code
Parse => strings into your own language

The End

Another bunch of interesting work he talked about were:
semr (Matt Deiters)
Xample (Ola Bini)

Conclusions

I haven't had much of an opportunity to follow up on these project but I must say they are all rather interesting. DSLs have influenced the way I write code for some time, I just did not know that the coding style I adopted used some of the patterns that Neal described here. That made me feel good :)

Also can't wait for Jays book!

No comments: