Code readability through conciseness

One of the things I love about newer languages like Ruby and Scala (and to a degree Python and Groovy) are the language features that allow you to dial conciseness up or down for readability. Take for instance the typical one liner for summing numbers in languages that support anonymous functions (which can be a bit cryptic in terms of readability):

Ruby
sum = [1,2,3,4].inject(0) {|result, value| result + value}
Scala
val sum = Array(1,2,3,4).foldLeft(0) ((result, value) => result + value)
Groovy
sum = [1,2,3,4].inject(0) { result, value -> result + value }
Python
sum = reduce(lambda result, value: result + value, [1,2,3,4])

One of the jobs of a good programmer is to make their code readable and in this case by naming the variable sum it’s obvious what’s going on to the right so if you can simplify the anonymous function or use syntactic sugar to reduce the amount of code there’s a good chance you can improve the readability as follows:

Ruby
sum = [1,2,3,4].inject(:+)
Scala can either reduce the anonymous function
val sum = Array(1,2,3,4).reduceLeft(_+_)
or in Scala 2.8 they added the sum method
val sum = Array(1,2,3,4).sum
Groovy can't reduce the anonymous function but has a sum method
sum = [1,2,3,4].sum
Python can't reduce the anonymous function but has a sum function
sum = sum([1,2,3,4])

Then even if the programmer reading the code is coming from another language and doesn’t know :+ or _+_ you’ll still have improved readability because they certainly understand how a sum is computed and can move past the line of code instead of having to read 3-4 lines of a for loop for something as simple as a summing operation. I love the balance of being very concise with the simple stuff so that I can be more verbose with the complex stuff, whereas in Java even the simple stuff is often extremely verbose.

There is of course the extreme of making your code too concise. Look no further than write-only languages like Perl to see where too much conciseness and obfuscation can lead to unmaintainable code.

This example is only trivial and somewhat contrived but I find that newer languages like Ruby and Scala give you significantly better tools to elegantly dial up or down the conciseness than Java or C# resulting in less code + more readable code = easily maintainable code.

As an example, I used just about every conciseness trick in the book I knew of when composing my submission for the 3rd Ruby Challenge’s Shortest Path Algorithm and I only discarded the ones that I thought obfuscated the intent. I like to think the reason my submission won was precisely because it was concise while still being readable. Writing that same algorithm with the same level of readability in Scala would be easy but in Java it would have tripled the lines of code hurting readability somewhat.

This entry was posted in Java, Ruby, Scala, Software Engineering. Bookmark the permalink.

8 Responses to Code readability through conciseness