Recently I’ve been spending time learning more about refactoring. It’s said that a great way to improve one’s code is to read other people’s code.
But how does one tackle reading code? One way is to try to figure out how a certain feature works. That is, one jumps into the middle of the code where a particular function is that one wants to understand. Then one traces those actions backwards. Sometimes this is the only way.
But thanks to git there is another way, which is more like reading a book: one starts from the beginning. I think it’s easier to understand a project and learn from it, when one can start understanding the project, while it was still small and see how to slowly builds on itself.
So this is how I did it for a PHP library that uses best programming practices: http://csv.thephpleague.com
First I cloned it from GitHub:
git clone https://github.com/thephpleague/csv.git
Then I ran the following to view the git history in reverse order (starting from the beginning):
git log –reverse
This shows me something like this
Now you can view details about the code changes on GitHub in this format:
Or in this specific example if I want to see the first commit:
If I want to see locally how the code looked like for a specific commit, I would simply do a checkout inside the directory containing the git clone:
git checkout [commithash]
Simply by going through this code, I learned a little about Travis CI (since I was curious, why the author added the file travis.yml) and for the first time I came across the Standard PHP Library (SPL) as the author uses a number of file classes in SPL.
This CSV library is well tested with PHPUnit, so I looked at the unit tests to help me better understand the code.
Next time when I’ll continue going through the history, I simply need to add the commit hash to the git log command:
git log –reverse 8ac83b9f8fc3d1a643c58ef134386a89bd547d46..
I’m actually really enjoying this 🙂
Later I plan to read some projects from https://github.com/gothinkster/realworld which has code for all kinds of programming languages.