You probably don’t need Java StringBuilder – Use a templating engine instead

NoString Builder

Does your code look like somewhat like this? Do you find \n in your code? Then you are doing it wrong. Building strings is a very, very cumbersome process. You’ll miss newlines, you can’t see what’s happening in the process, it’s inefficient if you want to wrap something and so on… Overall very error prone and time consuming. As a rule of thumb: When you write something, that could go into a file (e.g. a .tex file or a .html file), then write it into a file, and not intermixed with Java, C++ or Python code!

But I want to generate my file dynamically, so how can I do it?

Templating Engines

Instead of writing derpy stuff like

String start = "\\escaping \n too much \n"
String middle = "wow... that's weird"
String end = "homg the middle forgot the \n what amigonnadu noww\n"
String full = start + middle + end;

there is a more elegant concept for generating files dynamically. It’s called Templating Engine. In a templating engine, you write your file as you would have anyways, for example:

Hello, I'm just a .txt file... Almost... I have some special syntax enabled like variables denoted by $imAVariable.

And then I just continue writing. No chance to forget a new line.

… with a few “enhancements” to the default file:

  • write variables, for example with $variableName notation in Apache Velocity Templating engine.
  • write for loops, for example with
    #foreach ($name in $myArray)
     ...some normal derpy text
    put a $name in between
    lalala
    #end
  • … and some more functionalities, depending on the power of your templating engine.

Like this you’ll never miss a \n again and your file-to-be becomes much, much, much more readable. If you’re programming in Java, the best choice for you is probably Apache Velocity Templating Engine.

After writing your template file for example helloworld.vm

Hello $name!  Welcome to Velocity!

you can use Java to fill in the gaps, as in:

/*  first, get and initialize an engine  */
    VelocityEngine ve = new VelocityEngine();
    ve.init();
/*  next, get the Template  */
    Template t = ve.getTemplate( "helloworld.vm" );
/*  create a context and add data */
    VelocityContext context = new VelocityContext();
    context.put("name", "World");
/* now render the template into a StringWriter */
    StringWriter writer = new StringWriter();
    t.merge( context, writer );
/* show the World */
    System.out.println( writer.toString() );

Well and that’s it! Files built efficiently, readable, maintainable.

Summary

Writing files via string-concatenation is bad idea since the code is non-readable, errorprone and takes forever to write. A much better idea is to use a templating engine, where you’ll write your file as usual, with the exception of the dynamic parts. Those are inserted by the templating engine later on.

Leave a Reply

Your email address will not be published.