Wednesday, December 19, 2007

Data-Shining in Glimmer

If you take a Ruby gemstone and shine light on one of its facets, you get a glimmer of the same light from the other facets. This is similar to how data-binding works. When the user inputs data into one of the data-bound fields in a user-interface, you end up getting the same data from the other side of the binding whether it is a domain model property or some other field in the user-interface.

I attribute most of my knowledge on data-binding technology to fellow friend and past project colleague David Orme. Not only is he the founder and one of the original contributers to the JFace Data-Binding framework, but he also helped create and develop the Eclipse Visual Editor project and popularized the idea of duck-typing in Java.

During the days when he and I pair-programmed on an Eclipse RCP project for a client, we used to dream about simplifying the data-binding syntax we relied on, which looked like this at the time:

dbc.bind(nameTextBox, new Property(person, "name"), null);
dbc.bind(ageSpinner, new Property(person, "age"), null);

We fantasized about having a DSL like this one:

(nameTextBox, text) <=> (person, name)
(ageSpinner, selection) <=> (person, age)

Well, I am very happy to announce that this has finally become a reality in Glimmer with the power and flexibility of the Ruby language. Here is how it looks like in Glimmer:

[@name_text_box, :text] <=> [@person, :name]
[@age_spinner, :selection] <=> [@person, :age]

Amazing, isn't it!!!

The spaceship operator <=> clearly represents two-way data-binding at work. For example, the text value of the name_text_box is data-bound to the name property on the person model, so whenever the user enters text in the text box, data is automatically copied to the name property in person, and whenever the name property is programmatically changed, data is automatically copied to the text box and displayed on the screen.

I demonstrated in my last post how Glimmer Listens to SWT events, which can help you bind user actions such as pressing a button to application actions like logging in. Data-binding on the other hand greatly simplifies synchronization of data between the user-interface and domain-models, making it readily available for use when the user performs an action. By relying on listeners and data-binding, one can follow the Model-View-Presenter pattern by placing presentation logic in a presenter model, making it very easy to maintain and cover with unit tests.

Stay tuned for my next post where I will introduce a second method for data-binding in Glimmer and contrast both ways of doing it.

No comments: