Current version

v1.10.4 (stable)

Navigation

Main page
Archived news
Downloads
Documentation
   Capture
   Compiling
   Processing
   Crashes
Features
Filters
Plugin SDK
Knowledge base
Contact info
 
Other projects
   Altirra

Archives

Blog Archive

Undoing indentation hell

Have you ever looked at a piece of code and seen something like this?

if (...) {
if (...) {
...
} else {
if (...) {
...
} else if (...) {
...
} else {
...
}
}
...

I'm going into style matters again and I know this is going to be contentious, but personally, I find that code is hard to read when it looks like a big tree view. You have to mentally match the braces or highlight them individually to have the editor show the matching, and that's hard to do when there are so many of them. It's even harder when the top-level statements don't even fit on one screen. The worst case I ever saw had something like 12 levels of indenting and was more than 17 pages long... and I use a small font size. Most of the time this happens because a routine snowballs until it grows out of control, and no one has the time/experience/constitution to refactor it. This happens to me as well, and eventually I get annoyed enough that I have to perform a nesting exorcism.

I attack such monstrosities by a series of small, incremental transformations. This increases the chances that the code will actually still work by the time I'm done with it. I should note that these are best done only if you own the code or already have to do major work on it for other reasons; doing transformations like this willy-nilly is a good way to completely scramble history in a source code control system and nuke any chances of your team members successfully merging your changes with theirs.

Comments

This blog was originally open for comments when this entry was first posted, but was later closed and then removed due to spam and after a migration away from the original blog software. Unfortunately, it would have been a lot of work to reformat the comments to republish them. The author thanks everyone who posted comments and added to the discussion.