Saturday, November 22, 2014

Cleaning Code - Episode 1

This is a series of posts where we take a code snippet, analyse it's cleanliness and produce a simplified version of the code. The metric for cleanliness is arbitrary, but I hope most readers will agree that the modified code is simpler to deal with. This is optimizing code for the human brain.

Let's look at our first snippet, randomly selected from a moderate-sized C++ codebase.

This is a chunk of a C++ function called from a scripting language. It extracts parameters and builds a string from them.

What are the aesthetic issues? Same line declarations, single line complexity, repeated code, old C scoping for loops.

Cleaning up always gives the same benefits. Faster mental parsing. easier debugging/stepping, minimize surprises, canonical code shapes, easier rearranging. The tradeoff is increased verbosity, but text input is not a significant time expense comparatively.

Let's see the change-by-change commented version:

And the final version without comments:

Feel free to send in snippets for the next post! The messier the better!