Archive for 21st October 2007

Java static imports + Fluent interfaces + Builder pattern= DSL

After having written nothing for a long time I am back to talk about an interesting bunch of java features. I am talking about DSL in Java, not as clean and powerful as in Ruby but, I think, very interesting for Java developers.

Static import

So, let’s start with static import, a nice Java feature introduced in its 5th version. Until Java 5, we could only import classes for using in our code, so that, instead of using something as ugly as java.util.List list= new java.util.ArrayList() we could simplify by importing the List and ArrayList classes and omit the package class in the creation and usage of the objects.

But, what happens when we want to use static methods or properties of other classes?

MyFunnyClass.myMoreFunnierMethod(param)
MyFunnyClass.NotSoFunnyMethod(param)

Our code gets cluttered by retyping the class part, when this shouldn’t be necessary. Wouldn’t it be nice if we were able to express ‘I want to use the following static methods in my class, and then use them as methods defined in our class’ ?

We are lucky, Sun engineers introduced the static import feature in Java5. So how do we use it? This is a piece of cake:

import static mypackage.MyClass.interestingMethod
...
interestingMethod("Look ma, I don't need referencing to MyClass!")

or we can use wildcards instead:

import static mypackage.MyClass.*
...
interestingMethod("Look ma, I don't need referencing to MyClass!")
otherInterestingMethod("Look ma, I don't need referencing to MyClass!")

It doesn’t look very useful for what we usually code, and used incorrectly, can derive in a fist of method calls that we don’t know where they come from. But this feature is going to be crucial for DSLs design in Java…

Fluent interfaces

Fluent interfaces are a way of designing interfaces that allows us to chain method calls, making our code more readable. So, what does it looks like?

Without fluent interfaces:

Person person= new Person();
person.setName("John");
person.setSurname ("Smith");
person.setPet(new Dog("Charly"));
person.setClothingStyle(ClothingStyle.CASUAL);

With a fluent interface API:

Person person = new Person().name("John").surname("Smith").pet(new Dog("Charly")).clothingStyle(ClothingStyle.CASUAL)

Fluent interfaces make our code look much better.

Using chained methods is as easy as returning the object instance (this) at the end of each fluent method:

public class Person{
...
  public Person name(String name){
     this._name=name;
     return this;
  }
...
}

Fluent interfaces are compatible with having accessor methods (set* and get*) in our classes. Basically, the goal is to ease the API usage and uplift the readability/expressivity of our code.
You can get more information about fluent interfaces in Martin Fowler Blog.

Builder Pattern

The previous two features look very interesting, don’t they? And it seems that both of them can be used to improve our code readability, and actually they do. But there is a last feature that takes advantage of them , we are talking about the Builder Pattern.

Quoted from the Wikipedia:

The Builder Pattern is a software design pattern. The intention is to separate the construction of a complex object from its representation so that the same construction process can create different representations.

In short, we are going to have an object that facilitates the construction of …other objects! This implies that such a pattern is only useful when we design interfaces for objects that we are going to build up many times with different parameterization or to designing interfaces.

I am the sort of person that prefers an example over loads of paragraphs explaining it , hence go carefully through the following code:

package test;

import java.util.Calendar;
import static java.util.Calendar.* ;
import java.util.Date;

public final class TimeUtil {

    public static DateEx now() {
        return new DateEx(new Date());

    }

    public static DateEx tomorrow() {
        DateEx date = new DateEx(new Date());
        return date.add(days(1));
    }

    public static DateEx yesterday() {
        DateEx date = new DateEx(new Date());
        return date.subtract(days(1));
    }

    public static TimeUnit months(int n) {
        return new TimeUnit(MONTH, n);
    }

    public static TimeUnit years(int n) {
        return new TimeUnit(YEAR, n);
    }

    public static TimeUnit days(int n) {
        return new TimeUnit(DAY_OF_MONTH, n);
    }

    public static DateEx date(Date date) {
        return new DateEx(date);

    }

    private static final class TimeUnit {
        private final int type;
        private final int size;

        public TimeUnit(int type, int size) {
            this.type = type;
            this.size = size;
        }
    }

    public static final class DateEx {

        private final Calendar date;

        public DateEx(Date date) {

            this.date = Calendar.getInstance();
            this.date.setTime(date);
        }

        public Date toDate() {
            return date.getTime ();
        }

        public DateEx add(TimeUnit unit) {
            date.add(unit.type, unit.size);
            return this;

        }

        public DateEx subtract(TimeUnit unit) {
            date.add(unit.type, -unit.size);
            return this;

        }

        public DateEx clearTime() {
            date.set(HOUR_OF_DAY, 0);
            date.clear(MINUTE);
            date.clear (SECOND);
            date.clear(MILLISECOND);
            return this;

        }

        public DateEx firstDayOfMoth() {
            date.set(DAY_OF_MONTH, 1);
            return this;
        }

        public String toString() {
            return date.getTime().toString();

        }
    }
}

No worries, I am going to explain each line of code, or at least the more interesting ones:

import static java.util.Calendar.* ;

This rings a bell, I hope. In this case, importing Calendar static fields allows us to use them as:

            date.set(HOUR_OF_DAY, 0);
            date.clear(MINUTE);
            date.clear (SECOND);
            date.clear(MILLISECOND);

We are building a date builder, so we need another class especialized in the construction of java.util.Date objects. This DateEx inner class for:

    public static final class DateEx {
    ...
   }

The key point here is that DateEx is a construction utility that uses fluent interfaces, so that we can chain methods calls to DateEx objects like:

DateEx dateBuilder= new DateEx(new Date()).firstDayOfMonth().clearTime()

and finally get the date object:

Date date= dateBuilder.toDate()

This code seems alright, yet did you notice what an ugly code we are using to note “now” ? new DateEx(new Date()) ??? What the hell is this? If I want to express “now” I want something that actually does it, and “new DateEx(new Date..” doesn’t at all. Luckily, we might define convenient methods for that sort of things:

    public static DateEx now() {
        return new DateEx(new Date());

    }

Now, if we import the now static method in our class we can rewrite the previous code as:

DateEx dateBuilder= now().firstDayOfMonth().clearTime()

This is the kind of code that makes me happy (Yes, I know…). Look at it, and at first glance, you realize “hey, he is clearing the time part of the first day of the current month”.

Furthermore, we can add a couple of convenient methods to our new little API:

    public static DateEx tomorrow();
    public static DateEx yesterday();

There is also a TimeUnit inner class that allows us to express time units in order to perform time operations to our DateEx objects. For example, what if we wanted to get 1 month and 10 days before the current date? We can do it with our TimeUnit classes and static util methods as:

dateBuilder.subtract(months(1)).subtract(days(10));

Cooler than using our good ol’ Calendar friend.

What kind of things can we do with this example API?

package test;

import static test.TimeUtil.*;
import java.util.Date;

public class Example {
    public static void main(String [] params){

        Date date= new Date();
        System.out.println (date(date).add(years(1)));

        System.out.println(now().toDate());
        System.out.println(now().add(days(2)).add(months(1)).subtract(years(1)).clearTime().toDate());
        System.out.println(yesterday()+" - "+now()+" - "+tomorrow());
        System.out.println(now().clearTime().firstDayOfMoth());
    }
}

Neat, it is not perfect, a lot of brackets are needed which only mess the code up, but as I see it, we have improved the expressivity of our code. In any case, my advice is to learn a new language like Ruby or Groovy, it opens your mind and teaches you different ways of doing things.

On the other hand, Java 7 specification is going to define closures for the Java language, so in the future we are going to be able to do more interesting things!