When you read code, imagine typing it by hand. [01/06/2007 19:11:49]
Whenever you are confronted with unfamiliar code that you are having trouble understanding, imagine yourself re-typing it by hand.
For example, I'm trying to learn a little erlang for some WebDAV work I'm doing with YAWS. The following code is from the erlang course:
-module(mathStuff).
-export([factorial/1, area/1]).
factorial(0) -> 1;
factorial(N) -> N * factorial(N-1).
area({square, Side}) ->
Side * Side;
area({circle, Radius}) ->
% almost :-)
3 * Radius * Radius;
area({triangle, A, B, C}) ->
S = (A + B + C)/2,
math:sqrt(S*(S-A)*(S-B)*(S-C));
area(Other) ->
{invalid_object, Other}.
Stop for a minute and imagine typing the above code on a keyboard. It doesn't matter if you know erlang or not. In fact, this technique works even better when you're learning a completely new language.
Come on, just do it. :)
Now. Did you notice that sometimes functions in erlang end with a period, and sometimes they end with a semicolon? Did you see why? Do you remember which character introduced the comment? Did you notice that some things are capitalized and some things aren't?
When I first looked at the example, I didn't notice the semicolon-vs-period distinction. My eyes went right over it. But when I imagined typing it, I slowed down enough to notice the details. The semicolons jumped out at me immediately, and I had to stop and go back to the previous section where it introduced the syntax for functions to make sure I understood.
This is just a neat mental trick you can use to make sure you're really understand the code you're looking at, and not just glancing over it. And of course, you don't have to actually type it - in fact, I started doing this a long time ago for reading programming books away from my computer precisely because I didn't have a keyboard around.
