ScaLearning 2 – Reducing string-join to a line

facebooktwitterdiggdzonestumbleuponredditdelicious


Like many developers who make the journey from Java to Scala, I often find myself amazed at how much easier it is to do some things, or how much easier it is to express myself in Scala.

“ScaLearning” will be a series of short blog-posts just documenting little tidbits I find interesting, confusing, amusing, or otherwise worthy of talking about.

String Joining

I recently found myself writing a SQL generator that took a domain-specific query object and turned it into raw SQL. We had to write our own, as we needed to optimize several parts of the query, or face the rage of the customer when things were a little sluggish.

(It’s generally bad for business when the customer goes Hulk on you.)

As happens often in generating SQL, I found myself wanting to store a list and later convert it into a comma-separated string.

Java – First Attempt

StringBuilder result = new StringBuilder();
List items = Arrays.asList("a", "b", "c", "d");
boolean first = true;
for(String i : items) {
    if(first) first = false;
    else result.append(", ");
 
    result.append(i);
}
System.out.println(result.toString());

Sloppy. Three lines in the for loop, a local variable hanging around. It’s readable, but having to read 5-7 lines just to realize it’s a string-join seems excessive. Try again!

Java – Second Attempt

StringBuilder result = new StringBuilder();
List items = Arrays.asList("a", "b", "c", "d");
for(String i : items) {
    result.append(", ").append(i);
}
System.out.println(result.toString().replaceFirst(", ", ""));

Shorter, no local variable, but now we’re doing “unwork” to get rid of the leading comma. That’s an easy detail to miss, so fewer lines but not much more readable.

(I’m open to cleaner implementations! Comment with what you prefer.)

Scala

In Scala (and many other languages, ie: PHP) this is a simple one-liner.


val items = List("a", "b", "c", "d");
println( items.reduceLeft(_ + ", " + _) )
println( items.mkString(", ") )

Two ways, both one line. Both are readable, and I don’t have a real preference between them.

While readability and line count aren’t always so tied, the fewer lines a person has to read the faster they can read them. While I could easily write a method for Java to join Strings, this is just another example of how Scala seems to actively try to make my life easier.


facebooktwitterdiggdzonestumbleuponredditdelicious

Advertisements

2 comments on “ScaLearning 2 – Reducing string-join to a line

  1. Hi, I know you wrote this four years ago, but here’s the pattern I use when having to do that in Java:
    String separator = “”;
    StringBuilder result = new StringBuilder();
    for (String item : list) {
    result.append(separator).append(item);
    separator = “, “;
    }
    still verbose like your first attempt but without the if, and IMO still very much readable.

    • Not bad, that avoids the boolean and the creepy replace nicely. If I’m writing any Java 7 I may use that.

      I’ve been writing a lot of Java lately. My current Java approach since 8 is usually:

      List items = Arrays.asList(“a”, “b”, “c”, “d”);
      String result = items.stream().reduce((s1, s2) -> s1 + “, ” + s2).orElse(“”);

      Scala still comes out the more readable IMO. There’s less clutter, so you can focus in on the exact thing you want to do instead of all the fluff to set it up. Java 8 makes huge leaps forward though, and they did have to keep their old interfaces compatible, so I totally get why they couldn’t take it further.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s