Aug 17, 2012

ToString Mode and Auto ToString Mode of Rythm template engine

In a recent blog I've introduced SIM (String Interpolation Mode) of Rythm. This blog introduces another two new feature named TSM (ToString Mode) and ATSM (Auto ToString Mode) of Rythm

ToString Mode

This feature allows developers to create String toString() method for their class easily:

public class Address {
    public String unitNo;
    public String streetNo;
    public String street;
    public String suburb;
    public String state;
    public String postCode;
    // use Rythm.toString() API call
    @Override public String toString() {
        return Rythm.toString("@_.unitNo @_.streetNo @_.street, @_.suburb, @_.state, @_.postCode", this);
    }
}

As a comparison, previously you need to write toString() method in the following way:

    @Override public String toString() {
        return Rythm.render("@args Address _;@_.unitNo @_.streetNo @_.street, @_.suburb, @_.state, @_.postCode", this);
    }

So here are several facts about TSM:

  1. the sign "_" is used to refer to this object instance in the template
  2. You don't need to declare "_" use @args statement in TSM
  3. You must use Rythm.toString() interface instead of the normal Rythm.render() in order to use TSM

Auto ToString Mode

If TSM makes writting toString() easy, ATSM makes it even easier because you don't need to write the template:

public class Address {
    public String unitNo;
    public String streetNo;
    public String street;
    public String suburb;
    public String state;
    public String postCode;
    @com.greenlaw110.rythm.toString.NoExpose
    public String accessCode;
    @Override public String toString() {
        return Rythm.toString(this);
    }
}

And you can pass in parameters to configure the style and output fields:

@Override public String toString() {
    return Rythm.toString(this,
        com.greenlaw110.rythm.toString.ToStringOption.defaultOption.setAppendTransient(true),
        com.greenlaw110.rythm.toString.ToStringStyle.MULTI_LINE_STYLE);
}

The above code indicate that output transient fields which is not output by default. It also indicate that output should be in multiple lines. Refer to here for more details out the option and styling configuration.

You can use the following annotation to mark the fields that you don't want to output with Rythm's ATSM:

  • com.greenlaw110.rythm.toString.NoExpose
  • org.codehaus.jackson.annotate.JsonIgnore

Compare to Apache Commons Lang's StringBuilder

Like ATSM, org.apache.commons.lang3.builder.ReflectionToStringBuilder also allows to generate toString() output automatically. ATSM is slightly (around 20%) faster than ReflectionToStringBuilder. As a comparison, TSM is 2 times faster than it.

Foot notes: Rythm Template Engine is a static typed Java template engine using Razor like syntax. There is a full feature set demo hosted on GAE. The source code is hosted on github