How to read code written by someone else
From ArticleWorld
Reading someone else's code is an essential skill for programmers. If you are just starting out, it is even more important than it will ever be: learning from code written by someone else is one of the most valuable learning resources you will have.
However, code written by someone else but you often feels strange and impersonal. Just like with people writing book, everyone has their own habits, and you rarely have the luck of respecting the same guidelines as the other one.
Understanding code written by others is not too hard though: it is just an appliance of top-down design. Computer geeks may tell you top-down design is bad (and actually they are right in some cases), but this time, it works. Here is how to do it.
[edit]
Steps
- Start by finding the main function of the program. This is where everything starts from.
- As you encounter functions used, study each one of them. If you are lucky enough to be reading good code, function names will be quite self-explaining. If not, look over the code and comments to understand what everything does.
- Try to read the program gradually. Go down in the functions hierarchy, from those of the highest level, built on top of the lower-level ones.
- Try to understand class hierarchies, if they exist. They will often be the key. In fact, reading (good) OOP code is much easier than procedural code.
- If the project is very large, you can use a source analysis tool like SourceNavigator. These can map inheritance classes and provide comprehensive reports over the source file, allowing you to make your way around the code much easier.
- As soon as you managed to understand a part of the program, you may find it helpful to draw a diagram if you need it. Actually, it may help to draw these at all times. Draw header inclusion diagrams (showing header inclusion relationships between files), class inheritance diagrams and function calling diagrams.