I like me some compact code

Lately Groovy has been the language of choice for my scripting needs.

And slowly I am finding out how to do things in a groovy way instead of relying on shell commands that don’t always work as they would in a shell environment:

"scp user@host:*.java .".execute()

is just not the same as executing the same command in bash.

One of my pet peeves in Java is the way maps are handled. If you want to use a map to count occurrences of something you’ll have lots of fun doing so. It becomes even more hideous when you have multiple nested maps in your data structure:

if(!map.containsKey(keyA)){ map.put(key,new HashMap()); }
if(!map.get(keyA).containsKey(keyB)) { map.get(keyA).put(keyB,0); }
int counter = map.get(keyA).get(keyB)

Now for the same in groovy:

map[keyA][keyB] = map.get(keyA,new HashMap()).get(keyB,0)+1

I like it much better this way. I am sure many other languages allow for the same quick and easy way to accomplish this task. I just enjoy programming in a scripting language that is based on a language I know very well.

And by the way: I do not think that code written in scripting languages needs to be readable. If what you write is that important you should use a “real” programming language. Scripting languages are hazardous for code readability anyway as it is one of their defining features that they allow many shortcuts and are less strict on syntax than their grown-up counterparts.

PS: “Real Programmers Don’t Document If it was hard to write,it should be hard to understand”

By Yashima

Writer of code and stories


  1. Well, groovy is nice. But if you really want some nice, compact code you should try Ruby – the language groovy tries to imitate 🙂

    You can give an array a default value or a block of code that gets executed every time you have a miss in your hash:

    $ irb
    irb(main):001:0> map = Hash.new(){|hash, key| hash[key]= Hash.new(0)}
    => {}
    irb(main):002:0> map[‘bla’][‘blub’] +=1
    => 1
    irb(main):003:0> map
    => {“bla”=>{“blub”=>1}}

Comments are closed.