
Ask HN: How do you read code? - dsyang
Given a new project or an unfamiliar codebase, how do you go about reading and understanding the code?
======
chris_va
If you have access to a whiteboard...

List all of the directories (or classes, for a smaller project), and draw them
as boxes on the board.

Draw arrows between the boxes based on dependencies in the codebase (helps if
you have someone already familiar).

... Now start at the bottom of the dependency graph, and browse the code at a
medium level.

If you are going to be working in this codebase, go back through and browse
the code at deeper level, as if you were doing a code review. You can pretty
much assume that, every couple lines, there is always something you would
change about the code. Make a note of it.

At this point, you should have a fairly decent idea of how the code works, and
how you would change it.

~~~
dsyang
Thanks for the answer! It sounds like you're taking a bottom-up approach when
reading code. Do you think we can use software to build this dependency graph
and make it easier to read code?

~~~
chris_va
Yes, technically it is possible. Some languages (and build tools) are a lot
easier than others.

For purposes of learning the code, it may not be worth automating the
dependency graph. You will probably learn more from tracking it down than you
would if it was pre-generated for you.

------
nutela
Well you should always ask someone who has worked with it but lately I had to
come up quickly with a phone formatter class. I didn't have a clue how it
worked, no comments. So I start to rewrite some of it, run it see what
happens. Then when I learned what the stuff did I renamed it so it made sense
to me. Used real long variable names which were meaningfull not just tmp and
temp. Can really recommend it and it was very fast.

~~~
dsyang
Thanks for your answer! Your approach sounds like it works well if you have to
write a new component from scratch. What if you had to jump into an existing
codebase? How would you go about understanding the code?

------
zan2434
I look at what it does, do a quick architecture in my head, then compare it to
what I see. This helps me because before I even look at it I have an
understanding of how I think it should work rather than an absolutely clean
slate.

~~~
dsyang
What do you mean when you say compare it to what you see? How do you take the
files and lines of code you read and model it into a working architecture?
Where do you start? Do you think we could write a program that can make this
process easier? (also, thanks for your answer!)

------
sharemywin
if you have a good debugger then start at the beginning and run it line by
line. if a section looks understandable skip it.

~~~
dsyang
Thanks for your answer sharemywin! What if you were looking at a large project
that doesn't have a well-defined "beginning?" How would you pick what code to
run through the debugger first?

------
libovness
From left-to-right

