I was once again reminded of the constant controversy that surrounds the use of
goto by the two following posts:
Raymond Chen’s article on a COM trick to track the Explorer folder.
Rich Burridge’s thoughts on current programming style.
I enjoy reading Raymond’s blog immensely. Raymond is a consummate
Windows programmer and his blog contains a wealth of tips and tricks and
explanations of the Windows API that will make you see things in different ways.
This particular entry involves a long snippet of COM code that is, frankly
speaking, quite scary. Raymond made a point in this entry of not using any
external library (such as ATL, which cuts down the number of COM coding needed
for this kind of trick) in order to show exactly what is happening behind the
scenes. This is a laudable intent but I couldn’t resist adding the
following comment on his blog:
I believe the only point you’ve made is that only VB or C# should ever be
used to access COM
Raymond also made a point of not using goto in his code snippet and COM being what
it is, you need to constantly check for return codes and branch your code
appropriately, which results in the frightening code you can see in his column.
In the same spirit, Rich wonders if his coding style is not obsolete.
He observes that the various seminal papers and books, such as "goto considered
harmful" and "The elements of programming style", are over ten years old and
wonders if they are still relevant.
I can only salute Rich’s willingness to question his habits. Very few
programmers ever do that and once they have settled in a comfortable programming style and
set of tools, they hardly ever move away from it. It is a very healthy
attitude that I strongly encourage around me. And in case you are wondering, an easy
way to see if you are flexible is to stop using your current source editor and
try another one (i.e. try an IDE if you are using emacs or try Eclipse if you
are using IDEA).
Back to the goto problem, I believe Raymond’s code is the perfect
illustration of the few cases where goto actually improves the readability of
your code, and somebody was quick to point that out in the comments.
Cascading error cases is a good illustration of the power of goto’s, but you
need to remember that languages that support exceptions are slowly making this
kind of programming obsolete. There is no excuse to use return codes to
signal errors in Java, C++ or C#.
In the meantime, use goto sparingly and make sure you explain why you do so
in a comment.