Code Monkeyism

Programming is hard by Stephan Schmidt

The best Markup Builder I could build in Java

Using Groovy MarkupBuilders spoiled me for other ways to create HTML pages from code. Others think the same. But in some organizations you have to use Java and can’t use Groovy - at least when you can’t sneak it in.

So I tinkered around in Java to see what’s the best MarkupBuilder I can write with Java. Using DSLs and Fluent Interfaces (times(5).loop), I came up with a nice solution. It’s not Groovy, but it works.

   Page page = page(
      html(
        body(
          // A comment
          h1("Name games"),
          p("Hello ${coolName}, and hello", "id:${id}"),
          ul(
            new Loop("stefanie", "${name}") {
              protected Element each(String item) {
                return li(item);
              }
            }),
          loop("[${number}] ", "number", 1, 2, 3),
          text("..."),
          box("Warning private!"),
          p("Are you dynamic?"),
          // Some dynamic content
          new Action() {
            protected String with(Context context) {
              return "I'm dynamic, " + context.get("name") + ".";
            }
          }
        )
      )
    );

There are some tricks to make it better than most such Markup Builders in Java. I tried to use ideas from building DSLs in Java. Those are using static imports and varargs. The body, html and other elements are static imports from a MarkupBuilder class.

  public static Element body(String body) {
    return new Element("body", body);
  }
  public static Element body(Element... elements) {
    return new Element("body", elements);
  }
  ...

The varargs helps with adding a variable number of childs to an element:

h1(
   p("One"),
   p("Two"),
   p("Three")
);

Another problem is how to put object values into the generated markup. String concatenation leads to noisy code

  "Hello " + name + "!"

so I decided to use a expression language where the Java unified expression language comes to mind. There is an open source version available called JUEL. Now I can use

  "Hello ${name}!"

Attributes are also treated as expressions and seperated by commas, their names and values seperated with a colon.

   p("Hello ${coolName}, and hello", "id:${id}, class:list"),

Loop and Action classes allow for dynamic content.

          ul(
            new Loop("stefanie", "${name}") {
              protected Element each(String item) {
                return li(item);
              }
           }),

I’ve used the template design pattern for this, again with expressions, in a way Spring provides JDBC templates. Another nice idea is with static methods it’s also easy to develop custom, semantic tags, so the developer doesn’t need to know or see the actual HTML markup which is created. For example I used a box “tag” which translates to

public static Element box(String text) {
  return div(
                 p(text)
           );
}

Closures in Java 7 will make it much easier to write a MarkupBuilder. The Action and Loop inner classes will go away and the code will be more Groovy like. When they add syntactic sugar to create maps I can drop the “name:value, name:${value}” style for attributes and move to [ "name" : value, "name": value ] instead, which doesn’t need the EL to work. With some small things to add the MarkupBuilder can be used for JSON or XML.

I’m interested and open to all techniques and ideas to improve the markup builder.

Thanks for listening.

About the author: Stephan Schmidt is currently a team manager at ImmobilienScout24 in Berlin. Stephan has been working as a head of development and CTO. He has used a lot of different technologies in the last 20 years including Java, Rails and Python. Stephans main field of interest is maintainablity and productivity in software development. Want to know more? All views are only his own.

If you did like this article but you don't want to subscribe to new articles with your reader, you can follow me on Twitter or subscribe to new posts with your email:

Comments

Hello Stephan,

nice to see Java people working on concise and clear syntax for frequent problems. Nice work! Will you be releasing this code?

stephan

@Alex: I’ll release the code with an Apache license in the SVN sometimes next week, because of time constraints not as a project currently. Perhaps if I need it for XML/ JSON in Reposita, I’ll add it there. Thanks for the comment.

Quite elegant … well done man!

stephan

@Andreas: Thanks. Took quite some time.

Hristo

Here is better approach to get the same stuff for free:
1. Download the schema for XHTML.
2. Get JAXB and use the fluent plug-in for it to generate Java objects off XHTML schema.
3. Generate all the builder classes and for the complete XHTML with that!

One common problem with mark-up builders is that they quickly run out of memory for larger HTML content.

stephan

@Hristo: Do you have an example? I’ve tried a builder with fluent interfaces and XStream and it wasn’t as nice. Another version would be as an inner class, where you wouldn’t need static imports.

One wouldn’t use markup builders for larger content, I would use templates for that.

stephan

@Hristo: I could think of

new Page {
   protected String render() {
             withCss("names.css")
             .withJS("mine.js")
             .with(
                html(
                   body("hello world");
                ).withId("top");
    }

Anything fancier?

XHTML and a generater could be used for the static methods, too. An generator can be easly (~1h) written with velocity.

For perfomance one can consider writing elements on the fly, not keeping them in memory. Or compiling them to an array and optimize the compiled result. Either way you can get much more performance wiht an intelligent builder than with the naive builder approach one comes to mind at first.

[...] No signal, no noise. « The best Markup Builder I could build in Java [...]

Leave a Reply