The Holy Java

Building the right thing, building it right, fast

Posts Tagged ‘coding’

How stateless can you go?

Posted by Jakub Holý on April 29, 2011

I’ve attended an Oslo Coding Dojo named “How stateless can you go?” lead by Thomas K. Nilsson. The goal was to write a toString() method for a tree structure printing nodes with proper indentation w.r.t. their depth and then to make it as stateless as possible without any other regard (such as performance or cleanliness of the code).

It was very interesting to compare the original, stateful version and the resulting stateless one and to see the solution in various languages (Haskell, Clojure, Groovy, C#, Java, Scala) – it looked actually pretty similar in all.

What I’ve learned is that stateless (i.e. functional-style) code looks much cleaner for you get rid of lot of noise such as local variables and loops. In practice it is important to use a language with an efficient implementation of recursion (especially tail-recursion) and with data structures that lead themselves easily to recursive processing, i.e. make it easy and efficient to process the first element of a collection and do that recursively for the rest without modifying the collection (and providing utility methods like each). It is of course best to have languages that support map/reduce.

You can check the slides and various solutions at GitHub and see our primitive and stateless implementations below. (We did it in a nearly TDD-manner, but I won’t include the test here as it isn’t essential.)

Update: There are more solutions linked to from the meetup’s comments – search for “github” – and there is also a link to an article series for deeper discussion of challenges in writing pure and stateless code.

Read the rest of this entry »


Posted in Languages | Tagged: , , | 2 Comments »