It turned out that some guy named Donald Knuth once had a thought that code was not really all that easy to read when you compared it to a novel (at least that's what Wikipedia said). He reckoned that you have to write the code differently in order to make it easily understandable. You should write it as a narrative where the code is more of a foot note than actual content. A utility application should pull the code out of the novel and reassemble it into source code which can then be compiled. To me this sounded a very convoluted process, especially if you introduce a bug. How would you reference back to your novel from a stack trace? So I decided that I would try and have a go at writing code in a Literate style using no more than regular comments.
My first attempt really turned out to be a small amount of code with lots of narrative comments. Some of the advantages were apparent immediately. Writing code comments as if you were actually writing a novel requires you to explain and justify even the smallest decisions. I found myself writing comments like:
/* First I check the parameter for null because it is good practice and I don't want to get some obscure NullReferenceException later on. */And:
/* The previous implementation of this involved such and such which was a bad idea because ... */Maybe I just hadn't commented my code well enough before but I was sure the next developer to change that code would appreciate knowing that we already tried said approach. I even found myself double checking my most basic assumptions because I knew people would be scrutinising my choices in the future. The obvious drawback was that it took me a lot longer to write the code.
Another less obvious advantage was that writing Literately encourages code reuse. If you write a code novel every line of code has to be explained as otherwise it is there for no reason. Things don't tend to happen in novels unless the author has written it. I may not mind repeating a very simple function in a couple of places in code (that's a lie I mind it very much) but I really don't want to be documenting my choices for doing it over and over again - and then maintaining that documentation in the future.
Really though I have only scratched the surface. Don't worry if you are a Literate Programmer and think I have completely missed the point. I am very aware that what I have done so far is simply commenting my code verbosely. There is much more to Literate Programming than lots of comments and I will be diving deeper into it you mark my words. The point is that if I had not read Jeff Atwoods chapter I would still be completely ignorant of it's existence so thanks Jeff.
No comments:
Post a Comment