Archive for the 'Domain Specific Language' Category

Behaviour Driven Development with RSpec

Monday, April 24th, 2006

Back in February, I told you about Behaviour Driven Development using RSpec. Things have moved in very interesting directions since then.

First, and this is probably the most important, BDD is getting quite some attention, most notably at Canada on Rails. You should check out the Ruby on Rails podcast episode from the 17th of April, where Dave Astels makes an appearance alongside Tim Bray.

On the usage front, RSpec’s DSL has seen some tremendous progress. It reads like plain English. I have not decided yet whether I find it too wordy or simply astonishing! What do you think of this example.

Finally, RSpec now has a good-looking content-packed website complete with documentation, tutorial, examples and all.

There is simply no barrier to its adoption, it just needs traction within the development community. This is where you and me come into the picture. Let’s make RSpec a success, let’s all give it a go: gem install rspec.

You will be amazed at how much RSpec will impact the quality of your code because it changes your perspective on unit testing.

Comments are welcomed and encouraged! That’s all folks, see you next time!

RubyBeans revisited

Monday, March 6th, 2006

I have refactored the Rubybeans, a short example of Ruby metaprogramming code to make better use of Ruby’s metaprogramming API. I would recommend reading the original post to get the background information (in short: developing JavaBeans is a repetitive task that would greatly benefit from metaprogramming, RubyBeans are an illustration of how this would be done in Ruby). Since this post is also intended for developers not familiar with Ruby, I have tried to be quite verbose while explaining the code.

Buckle your seatbelts! Here we go:

class RubyBean
  def initialize
    @listeners = []
  end

I have just declared the RubyBean class. The initialize method is called everytime a RubyBean is created. It initializes the listeners instance variable to be an empty array. In Ruby, instance variables are preceded with @. Note that, instead of using [], I could have used Array.new. The square bracket notation is more commonly used in Ruby. In case it isn’t obvious, the listeners array will contain the property change listeners registered on this RubyBean.

Now, I add two methods to manage the listeners: one to register a listener on this bean, one to unregister a previously registered bean.

  def register_listener(l)
    @listeners.push(l) unless @listeners.include?(l)
  end

  def unregister_listener(l)
    @listeners.delete(l)
  end

In register_listener method takes one parameter l, the listener to be registered. Its code is almost plain english: push the listener at this end of the list of registered listeners, unless it is already there. The unregister_listener method is even simpler: remove the given listener from the list of registered listeners.

The code so far hasn’t used any metaprogramming features. But things are about to change!

In what follows I define a property class method. It is intended to be used by RubyBean subclasses to define their properties. For every argument it receives, the property class method will add 2 methods to the current RubyBean subclass: a getter and a setter.

  def RubyBean.property(*properties)
    properties.each do |prop|

In Ruby, a class method is defined by using the prefixing the method name by the class name: def RubyBean.property (this is equivalent to Java’s static modifier when it is used before a method). The *properties notation lets me capture a variable number of arguments as an array. The first line of the body loops through each element of this array. The name between the pipe characters is the name of the variable used to hold the current element in the block. For the time being, you can consider a block to be akin to an anonymous inline function. Blocks in Ruby come in two flavours do |param, other_param|... end and { |param, other_param|... } (note that if no parameter is required by the block, there is no need to use the pipe characters).

      define_method(prop) {
        instance_variable_get("@#{prop}")
      }

We’ve just written our last ever getter! The accessors in Ruby do not follow the JavaBeans conventions: the getter for a property is simply the property name (getName() is name) and the related setter is the property name followed by equal (setName(...) is name=). The previous code defines a method named using the content of the prop variable. The body of this method is defined by the block between the curly braces (this block has no parameters, so no need for pipe characters this time). The block will return the value of the instance variable named prop. In a double quoted string, #{…} is replaced by the evaluation of its content, here prop. So if the value of proc is name, "@#{prop}" will be "@name".

The following code defines how we declare setter methods. It also uses the #{...} notation, this time to concatenate the property name to equal, to create method name of the setter.

      define_method("#{prop}=") do |value|
        old_value = instance_variable_get("@#{prop}")
        return if (value == old_value)

The block for the setter accepts one argument, the value, as indicated between the pipe characters. As per Java conventions, we first make sure that the new value is different from the current value. If the values are the same, no need to notify the listeners, so we simply return.

Otherwise, we loop on all the listeners and notify them of which property is changing from what value to what value:

        @listeners.each { |listener|
          listener.property_changed(prop,
                                   old_value,
                                   value)
        }
        instance_variable_set("@#{prop}", value)
      end

Once all listeners have been notified, we set that property to its new value.

And finally, a bit of tidying up:

    end # loop on properties
  end # end of property method
end # end of RubyBean class

I hope this has enlightened you! Let me know!

Metaprogramming, Java’s downfall

Monday, February 20th, 2006

I have been a Java developer for almost 10 years and I must admit I really enjoy coding in Java. When I first discovered it, I was amazed by its API, the quality of its documentation, its simplicity and most of all its portability. With experience came a better understanding of the Java philosophy and a deeper understanding of Object Oriented concepts. Lately though, I have found Java to be a limiting factor to my productivity. I have identified the main reason behind this: Java lacks metaprogramming. Briefly put,metaprogramming is writing programs that write programs (see metaprogramming on wikipedia).

Here is an illustration of the problem. Everytime I want to write a JavaBean object, I have to make the class serializable, make sure the class has a default constructor, write getters and/or setters for all properties, write methods to register and unregister listeners for the bound properties, etc. It has to be done for every single bean you ever write. Coupled to the fact that unit tests for getters and setters are rarely written, leads to a very error prone process. It is easy to see that there is a definite pattern to this extremely repeatitive task, and obviously there are ways to ease the pain. Code generating tools like xdoclet and eclipse for example, do a decent job in this case. However, these tools suffer because they each use their own templating language and their functionality is usually limited to a C/C++ macro style of behaviour, agnostic of the language itself. By contrast, in a metaprogramming language, this templating and the code it generates are implemented in one language only. It is therefore possible to extend the language itself, by adding new constructs, rather than just develop the object hierarchy.

LISP is probably the quintessential metaprogramming language. LISP’s macros are so powerful that it has been able to adapt and incorporate every new programming paradigm. To my knowledge (and wikipedia’s), LISP (1958) predates all OO languages, as the concept was only being born, and yet CLOS is implemented in LISP itself and supports some features that other OO languages can only dream of (multiple dispatch for example). When AOP came about, it did not take long for LISP to have its own implementation: AspectL.

People usually object that LISP is unreadable. I suppose we will all agree that parentheses, like everything in life, must be used in moderation. But metaprogramming does not have to be implemented in a heavy and unreadable way. In order of increasing readability, I will point you to Io and to Ruby. Ruby uses metaprogramming, for example, to define accessors. But Ruby’s killer-app, Rails pushes this usage even further to provide a DSL for web development. See for yourself, I doubt you will find that Rails’s productivity claims are exaggerated.

For more information on metaprogramming and DSLs, I would recommend listening to the latest Rails podcast with Glenn Vanderburg and to check out Glenn’s blog, starting by this post. I also found Jose Antonio Ortega Ruiz’s blog, programmings musings to be a goldmine, see particularly: this post and follow the link to this good introduction to metaprogramming.

Follow

Get every new post delivered to your Inbox.