Friday, 14 March 2014

Goto Is not ALWAYS harmful

D. Dobbs Journal recently carried an article:

Is goto Still Considered Harmful?


Its about an security flaw in Apple's SSL libraries (or rather the one that secures things in the first place)  that is loosely related to "goto" statement usage in "C", though the actual bug has nothing to do with goto, but possibly a copy-paste or editing problem and supplemented by lack of proper unit tests. Its a very common question because many software company guidelines tend to discourage its usage, calling simply the use "unstructured" programming in a :structured" programming language.

However I have found usage of goto to be beneficial in two scenarios:

(1) Critical (performance sensitive and very-frequently-used/hotspot) parser code to implement a small state machine on one (somewhat large) function. done purely for performance and space efficiency reasons.
(2) Error handling, to avoid repetition of error handling code within the function and thereby enhancing maintainability and reducing footprint (like the code in Apple's SSL library). In large C language projects the footprint of error handling codes is sometimes as much as 20% and any optimization helps in improving readability & maintainability.

Maybe there are more cases which make the usage of goto attractive.

The overall idea should not be to out-rightly clamp down on usage of goto (as many QA departments tend to do), but be more prudent in its usage and ensure that the safety test net is especially strong in areas where goto is used.

No comments:

Post a Comment