Recently, Rob Pike wrote a little bit of history of Go, talking about how Less is exponentially more.. I’ve gone through learning Ruby in the last few weeks, and I want to give a minute exmaple of just how true this is, and compare Go (or, frankly, many other languages) to Ruby, and how Less is More.
Consider the barest, simplest control structure in Software Developement, the if statement. Lets think about this in Java where we often write something like the following:
if (a) {
b();
}
// or even
if (a) b();
// Or, the flip side
if (!a) {
// Do nothing
} else {
b();
}
Fairly simple; There’s only one real way of writing our code, even though using the else, we can see that, yes, there was a roundabout way of doing this. In Go, we have the same thing, basically, except we don’t have to use as many brackets. We can write, instead of that, the following.
if a {
b;
}
// Or, the opposite
if !a {
// Do nothing
} else {
b;
}
Note that we don’t have the simpler, completely brace free model, because Go makes braces mandatory on if blocks. So far this is all very nice, and it means that when you read a piece of code, there’s really only one or two patterns to look out for. Once you learn how an if works, you’re done.
Looking at how to do all this in Ruby, and we find a different way. Ruby allows many more ways of writing the same expression; There’s two reasons for this behaviour.
Let’s see what this looks like in practice, in Ruby.
# The simple way
if a
b
end
# and in the else branch
if !a
# do nothing!
else
b
end
# as a modifier
b if a
# as unless
unless !a
b
end
# as unless, the 'natural' way with an else
unless a
# nothing!
else
b
end
# as a modifier
b unless !a
Wow, what a set of combinations. I guess this is nicer for some people who don’t like reading inverted conditionals, but the confusion stems from having so many different ways of writing your code. Following the flow of control of some code in Ruby, means I need to keep my mind on reading the conditionals, seeing which of the patterns above the code falls into, and then following the program logic. In Go, Java, C++, or most other languages, the lack of choice makes it easier for me to concentrate on what I need to do.
On the small scale, this is what I mean by ‘Less is More’ . Having choice isn’t always a good thing. Most companies I’ve seen have Style guides for the programming languages they use, and often they say “We don’t use this feature in this language, because it confuses our engineers.” . I certainly agree, and even on the small things, like conditional expressions, they can make a big difference.