Archive for the ‘Programming’ Category.

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!

Paths absolutos

Voy a ser corto. Tatuaros en la frente: ¡NO UTILIZARÉ PATHS ABSOLUTOS EN MI APLICACIÓN!

Al resto del equipo no le gusta descargase una clase en la que lo primero que te encuentras es:
"D:\workspace\proyectox\drl\fichero.drl"

¡Usa el classpath y rutas relativas!

Sí, hay excepciones a la regla, pero generalmente aplican a sistemas de producción, no de desarrollo. Por ejemplo, el administrador puede querer que los logs vayan a /var/logs/aplicación, pero tu no quieres poner los logs en tu equipo en C:\Documents and Settings\bob\Mis Documentos\logs.

You Need Code Reviews

Look at this code:

(within a while body)

...
if (log.isDebugEnabled()) log.debug("Parsing line " + (lineNumber++));
...
lineNumber used here
...

You might be wondering: what´s wrong with it? Well, it turns out that this sort of construction it could become extremely difficult to spot in certain conditions. Imagine a hypothetical situation where this code is not working properly in the production environment, and meanwhile the developer in charge of this block of code -the guy as cool as a cucumber- is totally sure about the correctness of it. Okay, you got it, you may be thinking of me: “How noob this guy is!”; but Hey!, sometimes you are toiling late in the night and this kind of bugs pass unnoticed until you receive an email from your Development Manager muttering:

Subject: Potential bug

I have come across with this statement -incidentally- while surfing the code. Beware that the log will be printed out only if the log level is set to DEBUG, so the lineNumber variable won´t be incremented.

All the best,

Your Development Manager

Guess which level the Production Support had established in their environment? Fortunately, I started off saying “Imagine a hypothetical situation …“.

Thinking Recursive

english.gif My first attempt to write something in English (Don´t cut me some slack!)

Basically, the programs written in functional languages like Lisp or Haskell are based on function definitions. I don´t want, by no means, to give a thorough explanation of the features that functional languages offer because, among other things, I am not an expert on such languages (although I´d like to). I am writting this because not until I tried to implement some probs kinda recursive-natured, did I find how quick & fun this kind of programming style is.
Let´s set out to implement a naive algorithm for sorting lists in Haskell, so for a given input list, we get the corresponding sorted list. The function sort takes an argument of type list and returns a new list representing the former one in order.

-- Sort a list
sort :: Ord a => [a] -> [a]
sort [] = []
sort (x:xs) = insert x (sort xs)

The first line comprises the function definition, which takes a list of elements of type a, and returns the same type ([a] -> [a]). The string “Ord a” restricts the potential members of the list to types compliant with the ordering rules (integers for instance). But this is Haskell specifics, not very appealing. Let´s go to the implementation. The second line is the implementation of the function for an empty list, which in turn returns an empty list.
Lokking over the last line, we can notice that it defines how a non-empty list, (x:xs) being x the first element and xs the remainder, is going to be sorted. For that, it makes use of a new function named insert. Here you are:

-- Insert an element in to a list, maintaining the order
insert :: Ord a => a -> [a] -> [a]
insert y [] = y:[]
insert y (m:ms)    | y <= m = y:(m:ms)
                   | y > m     = m:(insert y ms)

This second function takes two arguments, the first one being an element of type a, and the other a list of elements of the same type. Same type restrictions as in the parent function. The return value is another list. The trivial case (insert y [] = y:[]) concatenates an element with an empty list. The general case says (last two lines): “if the element to insert is less or equal than the first element in the list, concatenate them. Otherwise, join the first element in the list with a recursive call using the same element and the remaining elements in the list”. Easy ha!

Let´s see the recursive call stack for this execution:

sort [9, 3, 5]
       |
insert 9 (sort [3, 5])
       |
insert 9 (insert 3 (sort [5]))
       |
insert 9 (insert 3 (insert 5 (sort [])))
       |
insert 9 (insert 3 (insert 5 []))
       |
insert 9 (insert 3 5:[])
       |
insert 9 (3:5)
       |
3:(insert 9 5:[])
       |
3:5(insert 9 [])
       |
3:5:9:[]
       |
[3, 5, 9]

Yay! Some may argue that this implementation is time-taking, that it does too many recursive calls even for small inputs. A complete resource waster. I couldn´t do anything else but agree with that, but, you know what? I don´t care! It´s just this code´s neatness what makes me feel thrilled. I look at it and I think: “Ey dude! It´s as pretty as a picture!”. If you still feel like sprucing it up, a good starting point could be this one.

Another good point in the functions above is that I didn´t say that the input list had to hold numeric elements! Surprisingly (not for an expert), the following execution outputs a nice result (guess why?):

sort ["Water", "The", "Dead", "In"]

... (call trace left out)

["Dead","In","The","Water"]

For the most part, this is what I wanted to show here. Isn´t it worth the hassle? At least for me, no doubts.