So Java is more complex than Scala? You must be kidding

My esteemed colleague Michael Duerig posts about Scala code being simpler than java.

His Scala example is beautiful, no question about it:

object ScalaMain {
  case class Person(name: String, age: Int)

  val persons = List(
    Person("Boris", 40),
    Person("Betty", 32),
    Person("Bambi", 17))

  val (minors, majors) = persons.partition(_.age <= 18) 

  def main(args: Array[String]) = {
    println (minors.mkString(", "))
    println (majors.mkString(", "))
  }
}

Though I wonder how many Scala programmers are actually able to come up with such concise and elegant code.

Michi’s corresponding java example, however, is…let’s say horrible. Like making things as complex and bloated as they can be.

Here’s my (slightly) more elegant Java version:

import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;

public class Person extends HashMap<String, Object> {
    
    public Person(String name, int age) {
        put("name", name);
        put("age", age);
    }
    
    public static void main(String args[]) {
        final Person [] persons = {
            new Person("Boris", 40),
            new Person("Betty", 32),
            new Person("Bambi", 17),
        };
        
        List<Person> minors = new ArrayList<Person>();
        List<Person> majors = new ArrayList<Person>();
        
        for(Person p : persons) {
            if( (Integer)p.get("age") <= 18 ) {
                minors.add(p);
            } else {
                majors.add(p);
            }
        }
        
        System.out.println(minors);
        System.out.println(majors);
        
        // Output:
        // [{age=17, name=Bambi}]
        // [{age=40, name=Boris}, {age=32, name=Betty}]
    }
}

Not bad hey? 37 lines all included, and although Java does require more boilerplate code, it’s not too bad.

All this is kinda tongue in cheek, ok? We could start all sorts of flame wars about type safety, generics and dynamic programming – my point is just that elegant and ugly code can be written in any language.

Scala definitely helps with conciseness, but in my opinion Java does not require things to be as bloated as some of those language wars examples show.

I’m on my way to Michi’s office to sort this out face to face as well ;-)

Update: face to face discussion went well, we agreed to not start religious wars…and in the meantime, here are two additional (and more serious) posts on the subject:

13 Responses to So Java is more complex than Scala? You must be kidding

  1. Julian Reschke says:

    Thanks, Bertrand. I was hoping that somebody would reply with a saner Java version :-)

  2. Lean says:

    So, a Person is a HashMap? wtf!

  3. bdelacretaz says:

    I knew someone was going to notice this HashMap thing ;-)

    Actually, why wouldn’t a Person be a Map of named things? That’s what many dynamic languages do anyway.

    • Lean says:

      IMO I think is not because in that example you are using inheritance for code reuse rather than polymorphism.
      You can achieve the same using fields and overriding toString() and would be simpler enough I guess.

      Cheers.

    • ittay says:

      So you showed that while creating a class that is not usable outside (no fields or accessor methods) and by being very inefficient in time (boxing, casting, hash access) and space (hash table) you managed to get to something that is still longer.

      Not very convincing…

  4. bdelacretaz says:

    Of course, fields and toString() would be a more standard way of doing things…I guess I wanted to show that you can also be clever and take a few shortcuts in Java when there’s a good reason. Like convincing a colleague (not!).

  5. abp says:

    Or using HashMap extending classes as the new and concise java?

    “Though I wonder how many Scala programmers are actually able to come up with such concise and elegant code.”

    Thats a matter of experience, i think. Show me the java programmer that comes up with extreme elegant apis and respects all java contracts etc. the first time programming. Every language needs some years of experience, for real mastery. And scala seems quite worthwile.

    • bdelacretaz says:

      @abp, absolutely agree that experience in a language makes all the difference, that’s also what I meant when saying “elegant and ugly code can be written in any language”.

      I also don’t mean to discourage people from learning Scala – it’s certainly a great language. I was mostly reacting to Michi’s extremely ugly Java example ;-)

  6. Grzegorz Kossakowski says:

    Hi Bertrand,

    Noting that this is tongue-in-check blog post I must mention a few things.

    First of all, I’d say that most of experienced Scala programmer would come up with such code as it doesn’t involve anything special. The only thing is to know that “partition” exists. Most folks learning Scala quite quickly come to that idea that learning as many of standard collection’s methods as possible is the best investment of their time, though.

    In statically (to some extent) typed languages like Scala and Java projecting class (as a data type) onto HashMap makes little sense, really. Projecting class onto tupple makes much more sense and this is what Scala does with cases classes.

    Now, what if you wanted to to find if there is any adult?

    In Scala you’d write:
    persons.exists(_.age >= 18)

    How much of noise will it take in Java to ask this question?

    Now, let’s try something more fancy. Let’s check if list is sorted in order that you order first by name and then by age.

    You’d do:
    persons.sliding(2,1).forall {
    case x :: y => if (x.name < y.name) true
    else (x.name == y.name && x.age <= y.age)
    }

    Again, I didn't use any sophisticated constructs from Scala.

    I happen to work on a project (http://scalagwt.gogoego.com/) which involves dealing with both Scala and Java code both in terms of programming these languages and compiling this languages. To not make my comment any longer I only say that GWT would be so much easier to work with (in terms of working on it's internals) if it was written in Scala…

    • bdelacretaz says:

      Grzegorz, great to hear from you and thanks for the additional examples!

      IMO the first one is a great example of the conciseness of Scala. The sliding iterator…that’s cool but not as obvious, by far.

  7. Grzegorz Kossakowski says:

    (how one replies to a reply?)

    I agree that sliding is far less obvious but once you discover it there’s no way back. Imagine how much work it does for you including handling special cases like empty list, singleton list, etc. :)

    Actually, my first solution was like that:
    (persons zip (persons drop 1)) forall {
    case (x, y) => …
    }
    This is probably even less obvious for Java programmer but it’s really basic technique in functional programming :)

    Anyway, I just wanted to point out that in searching for concise and readable examples I forgot to point out what’s the most important point about all these examples. It’s called “abstraction” that we all love :)

    Scala 2.9 will introduce parallel collections which means it will be automatically parallelizing operations performed on collections.

    If persons won’t be already a parallel collection all it takes is to say:
    persons.par.exists(_.age >= 18)

    to make use of this new Scala’s library. The library will execute exists on separate segments of persons in parallel using very lightweight techniques that don’t add that much of overhead.

    This is where you see real power. Scala allows you to abstract from the order of iteration over collection and then new libraries can utilize it in very clever ways.

    At the same time, this is the biggest weakness of Java that it allows so little abstraction. :-(

  8. […] argumentation about simplicity vs. complexity of Scala. WarpedJavaGuy’s, Michid’s and Betrand’s Blog Posts flamed discussion and a lot of interesting comments and thoughts about the […]

  9. Alex says:

    Java code is always horrible. To write and to read both. One of the most pointlessly verbose languages around.

%d bloggers like this: