- How to read code without ripping your hair out
- Sun-li Beatteay
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: Mcskiller
- Proofread by xionglong58, Endone
- How to write code
- Read the code
- Do this every day
This is the requirement I gave myself when I switched to programming two years ago. Fortunately, there are many online coding courses and tutorials that teach you how to write code, but they rarely teach you how to read code.
This is an important distinction. With the number of coding boot camp graduates going into the tech field skyrocketing. Emphasis on reading source code becomes more important. Brandon Bloom writes:
If it’s running on your machine, it’s your software. You’re responsible for it, so you have to know it inside out.
Although every programmer should read the source code, that’s not the case. Many programmers don’t want to read source code because it’s hard to read, undermines their confidence, and makes them feel stupid. I know, because that’s how I feel.
It’s just the wrong way
As I read other people’s code, I came up with a three-step reading method. Maybe some people are already following these steps, but I’m sure most people aren’t.
Here’s how I did it.
1. Pick a point that interests you
Thinking back to the first time I read the source code, it was a disaster.
I was learning Sinatra, and I wanted to get a better understanding of the underlying mechanics. However, I didn’t know where to start, so I found its Repo on Github and opened a random file. Joking aside, I did.
I thought I could spend the afternoon studying it and have it all mastered by dinner time. After all, it’s easy to read my own code. What’s the difference between reading someone else’s?
We all know what happens next. I felt, so to speak, like I had hit my head against a wall of words.
There’s so much I want to learn at once. Many beginners make the same mistake when they first read source code.
Mental models are built bit by bit, and so should reading code.
Don’t try to digest 1,000 lines of code with consistent effort. Focus on one topic. It is even better if you can refine it to a single method.
Having a detailed focus allows you to distinguish what is relevant and what is not. There is no need to ignore irrelevant things.
However, choosing a specific topic won’t solve all your problems. Knowing where it is in the code base remains a challenge.
That’s the problem with step two.
2. Find an entry point
Now that you have a goal you want to learn, what should you do next?
Fortunately, programming languages come with inspection tools.
The class of the object, the ancestor of the class, the stack trace, or the owner of some method, are features that most languages have. No matter which one you want to know, once you start analyzing your code base, you run into a number of problems.
Rather than explain the concept in words, it is faster to show it in code.
To analyze
Let’s say I want to learn more about ActiveRecord. I’ve then narrowed my focus to the Belongs_to method, and NOW I want to see how it affects the ActiveRecord model.
ActiveRecord is part of Rails and is built in Ruby. Ruby provides a number of development tools.
My first approach is to use a debugging tool, such as pry gem, to dissect my ActiveRecord model. For the previous assumption, this is the code for the model I chose to debug.
class Comment < ActiveRecord::Base
belongs_to :creator, foreign_key: 'user_id', class_name: 'User'
belongs_to :post
binding.pry
validates :body, presence: true
end
Copy the code
Note the binding.pry statement. When Rails encounters this line of code, PRY suspends the application mid-execution and opens the command line prompt.
Here is an example exchange I used on the console while researching the Belongs_to association.
-
All of my input comes after PRy >.
-
=> Displays the console output.
pry> class = belongs_to(:post).class
=> ActiveRecord::Reflection::AssociationReflection
pry> class.ancestors
=> [ActiveRecord::Reflection::AssociationReflection,
ActiveRecord::Reflection::MacroReflection,
...omitted for brevity ]
pry> defined? belongs_to
=> "method"
pry> method(:belongs_to).owner
=> ActiveRecord::Associations::ClassMethods
Copy the code
If you don’t quite understand Ruby and this exchange is confusing, take a look at my tips.
-
When belongs_to: POST runs, it returns an instance of the AssociationReflection class.
-
MacroReflection is the parent of AssociationReflection.
-
Belongs_to is a class method, it is in the ActiveRecord: : ClassMethods module defined on inside the Associations.
Now I have some clues, but which one should I follow? Because I’m more interested in the belongs_to method itself than its return value, I decided to look at the ClassMethods module.
3. Follow the clues
Now that you have a target you want to follow, all that’s left is to follow it until you find your answer. This may seem like a simple step, but this is where most beginners get it wrong.
One reason is that the repository does not have a directory. We let maintainers organize their files in a readable way.
For large projects with many maintainers, this is usually not a problem.
But for a small project, you might find yourself wading through file by file, deciphering name variables one by one, and then come across the “where did this come from” situation many times.
Making the search
One tool that makes this task easier is GitHub Search (we’re assuming the project you’re reading about is on GitHub). Github search is handy because it displays all the files that match the search query. It also shows the location in the file of content that matches the query.
To get the best results, you need to make your search as specific as possible. This requires you to have an idea of what you are looking for. Blindly searching Github won’t work.
Return to step 2 for an example, I tried to ActiveRecord: : Associations found ClassMethods module. In layman’s terms, I’m looking for the ClassMethods module in the module Associations, located inside the ActiveRecord module. Also, I’m looking for the Belongs_to method.
This is my search query.
The results showed exactly what I was looking for.
More research may be needed
Github searches will significantly narrow your search area. As a result, it’s easier to find an entry point into your code base.
Unfortunately, finding a class or method doesn’t always answer the question. You may find yourself jumping from module to module until you understand the big picture.
In my case, the belongs_to class leads me to the build method in BelongsTo. This leads me to the parent class of Association.
Finally, I found out that belongs_to had Rails add several instance methods to my model, including getters and setters. It does this using an advanced programming technique called metaprogramming.
Rails also creates an instance of Reflection class to store information in Association.
From the Rails API documentation:
Reflection enables the ability to examine relationships and aggregations between ActiveRecord classes and objects. For example, this capability can be used in the Form Builder, which takes an Active Record object and then creates input fields for all properties based on its type, and displays its associations with other objects.
Pretty neat.
conclusion
I can’t promise that parsing someone else’s code will be fun, but it’s worth it. It adds a key skill to your tech stack and gives you more freedom. You will no longer rely on full documentation and examples, and while documentation is great, it is not a panacea. As Jeff Atwood puts it:
You can probably find the best, most authoritative and up-to-date documentation, but no matter what the documentation says, the source code is the truth.
So go practice this skill!
I’m sure there’s something you’ve always wanted to know by now. Don’t get hung up on the size of your code base. Open up your repository of favorite frames and start learning. If you follow the steps IN my article, you will soon become a source code expert.
If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.