What techniques can anyone suggest for understanding a new piece of code?
Here are some of the things I find sort-of work:
1) Print the code out, on a colour printer, with syntax highlighting, single sided. Spread it out on a desk. Then go through it: a) Highlighting start of functions and 'blocking off' large statements. b) Highlighting significant calls throughout e.g. calls out to other code or functions that interact with the real world (e.g. move camera lens). c) Flagging bits that really don't make sense. d) Adding handwritten comments in the margin explaining in general terms what a block of code does.
2) Simultaneously, have an editor open with the code available and a good grep tool to hand. When something needs explaining in the hardcopy, search for it here.
3) Simultaneously have the code running in a debugger (if you are lucky enough to have complied and working code) and make use of the call stack to see what's going on.
Problems with my approach:
1) I get distracted going through the code from start to finish and spend too long looking at trivia rather than finding the core functions.
2) I spend too long writing down long function names on pieces of paper and end up with a scrawled mess. For any badly structured piece of code the paper is a bit useless.
3) I feel like an idiot with my desk covered in highlighted pieces of paper.
Any tips or useful tools for analysing the code structure? I quite like paper since you don't spend so long mucking about with 'making the boxes line up pretty' but I wonder if I couldn't do better.
I strike this problem on average twice a year when I get handed a new piece of code to modify or maintain. It must be pretty common out there - after all, how often do we get the luxury of writing code from scratch?