[Not Publishable]Reading Code
My 2 pennies on the art and science of reading code with limited comments
I recently happen to go through a tiny piece of code in Python that uses nothing but only the standard keywords, which I took a bit to understand. It was mainly due to the lack of code comments that tells about the 'why' behind the code.
The code is below:def combinations(iterable, r):
# combinations('ABCD', 2) → AB AC AD BC BD CD
# combinations(range(4), 3) → 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = list(range(r))
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
source: https://docs.python.org/3/library/itertools.html#itertools.combinations
The main difficulty I was facing was with the for loop with the break statement. The breakthrough came when I decided to contrast the behaviour of when a piece of code is present to that when it is not present. Here when I commented out the for loop, and ran the code and error was through that indicated that a variable is unbound, which was the turning point in my understanding of the code. When I saw it I quickly realised the tight coupling between two regions of code which for some reason I was overlooking till then.
Two general lessons in reading others can be drawn from this:
- Find the seams in the logic as much as possible, and try to map different regions of code into each sub-logic.
- After doing it, the regions of code that remains still without a clue could be tackled like what I did by trying to mechanically elicitate understanding by enable and disabling those regions of code and observing and contrasting the beviour of the overall system in each case.
A similar idea that I saw online is:
Code is not like a novel
First, don't be tempted to read the code like a book, starting at the beginning and reading cover to cover. Actually, you might want to skim the whole thing at first just to get a rough overview, but if you insist on understanding each and every thing before you understand the next, you will be lost for sure.Let the machine help
The trick in understanding a large piece of code without spending a lot of time is to get the machine to help explain the code to you.
source: https://web.media.mit.edu/~lieber/Teaching/IISDW/Read-Code.html
