4 December 2007
I don't not write much production code these days, but I still spend quite a few hours writing code. This code is a particular form of code, meant for explaining ideas in books. Book code isn't quite like real code, there are some different forces to consider when writing it.
One question is the choice of language. I need to write code in a language that as many of my readers can read and follow. I try to write about ideas that are platform independent, but I need code to be precise. So I need to pick some widely readable language that people can follow.
In my early days the two largest OO languages were Smalltalk and C++. Both had faults, Smalltalk was too weird for non-smalltalkers and C++ was too full of sharp edges to get right. Java was a godsend for me. Anyone with a C/C++ background could read it. Even most smalltalkers could hold their noses and understand what I was coding. That's why the refactoring book was in Java.
Later on .NET appeared. The nice thing here was the C# was mostly the same as Java, so I could use the two pretty interchangeably. I liked to use both to reinforce that the ideas I was writing about were useful in either case.
That situation is getting more difficult these days, particularly with writing about DomainSpecificLanguages. Java and C# are diverging, and some things I want to illustrate require features that neither of them have. I do much of my personal programming in Ruby, which is very well suited to DSLs, so I will use Ruby as my first choice for this situation. But other languages have contributions too. I need to balance illustrating various language capabilities for DSLs against letting the book become a hodgepodge of language tidbits.
Another issue with book code is to beware of using obscure features of the language, where obscure means for my general reader rather than even someone fluent in the language I'm using. A good example of this is that when I write examples using Ruby, I've often shied away from using collection pipelines, even though I use them heavily in my own Ruby code. This is because I consider that programmers from a curly-brace background will find it harder to understand those kinds of expressions. So I sacrifice fluent Ruby in order to reach those readers.
Again this is much harder for a DSL book. Internal DSLs tend to rely on abusing the native syntax in order to get readability. Much of this abuse involves quirky corners of the language. Again I have to balance showing readable DSL code against wallowing in quirk.