How to Read Other People’s Code — and Why
If you are a professional software developer, or aspire to be one, you will need to know a lot of of things. Various maths, stats, languages, frameworks, methodologies, tools, etc. Fads and buzzwords will come and go, all during your career. You’ll master some, ignore some, laugh at some.
But aside from the desire and ability to work in abstracts for concrete results, there is one skill that is an absolute must-have.
You have got to be able to read other people’s code.
Reading other people’s code is hard graft. Few young developers look forward to perusing other folks code, to mapping out the functionality, to learning the ins and outs of how it works.
But it is absolutely necessary.
We’ve all been there: faced with a mountain of code (which, by the way, is currently working in production) written by the guy who left, the girl who is on vacation, the guy whose wife is having a baby, who is on his honeymoon, who has won the lottery. The boss needs a new feature added or a bug fixed, and you’ve never looked at the code.
But you’re on the hook for it. What to do?
The essence of reading code is fairly simple: build a reasonable mental model of the code in question. If you have a working model of how the code works, you can make changes with some expectations as to how it will react. There is no magic bullet; it is sometimes harder to read and understand code than to write it in the first place. Here are some approaches that can pay off:
First — Do No Harm
This is a simple prohibition against common temptation. Go ahead and add logging code, maybe some stats recording, etc. But test rigorously to ensure you don’t change how the code works; understanding working production code is hard enough without mutating its behavior. This prohibition also includes resisting the temptation to “just write it from scratch” yourself. Bad, bad idea to do so under the gun, with a deadline, in a domain your not expert in. And if you haven’t written code for the problem domain, you are not expert in it.
Unit Tests — Use’em if you Got’em
Unit Tests are wonderful if they exist. Twenty years ago, they were rare in software — nowadays they are much more common. If you have them they are the best, truest documentation of how the code works. Start here, play here, make changes to the unit tests and observe what happens, take notes, learn all you can. Try to write some new tests to test your understanding. This is your chance to poke and prod at the code and observe how it responds. Think of Unit Tests as the petri dishes of software lab research.
And if there aren’t any Unit Tests, write some.
Read the comments, but don’t believe them
This goes for design documents, requirements, user stories, etc. Code documentation has an aging component to it, and artifacts like design documents are rarely representative of the code. Comments are “younger” in some sense, but we’ve all seen tons of comments that make no sense. So read the comments and such, but think of them as archeological hints at best. They tell you what the code might have been trying to do, sometime in the past.
Make a separate model of the code
This is the goal of reading the code in the first place, but here I mean make a real model. On a whiteboard, with a mind-map, on a pad of paper, with small action figures, I don’t care. But make a model of some sort. Seeing it outside your head in some form will help you firm it up and point out wholes.
Don’t Hate the Code
You can get sucked into hating the code, merely because it is not yours. Software people tend to be equipped with ample egos, and other people’s code can offend. But realize, their working code is better than your imagined code, because their working code exists right now. So put your ego aside and learn the code in front of you.
There is an important but oft-overlooked point to keep in mind when looking at other people’s code: the folks who built it the first time had a model for it, and it made sense to them. Respect them enough to look for that model. I will concede some peoples’ minds work in strange ways.
Reading other people’s code can be an overlooked skill in these days of rapid prototyping, shoestring start-ups, and hero coders. But you’d be well served to learn to read code. One might diffidently point out that the much of the open source software movement (is it a movement?) requires you to read other people’s code.
Learn to read code quickly and well; it’ll make you a better developer.
Update: this turned out to be my most popular post ever. I completly attribute this to me writing it while at Strange Loop 2009 in St Louis. Great conference!
Explore posts in the same categories: TechTags: Artisan, Design By Gravity, Software Development
You can comment below, or link to this permanent URL from your own site.
October 23, 2009 at 2:50 am
I agree. In real life, most programmers need to read other people’s code. Perhaps the most difficult part for me was not to hate the code. It needs getting used to.
“And if there aren’t any Unit Tests, write some.”
– Would be a big problem if the code you are working on is un-testable. UGH! 😉
October 23, 2009 at 3:11 am
“…archeological hints” classic. I gotta use that!
October 23, 2009 at 3:39 am
“the folks who built it the first time had a model for it, and it made sense to them”
Unfortunately in my experience, this is rarely the case. This comes through very painfully when you actually ask people to explain their code. What it comes down to a lot of the time is that they just kept hacking away at it until it worked. Any mental model they had was abandoned along the way, and they have almost just as much of a hard time understanding their own code as you have.
Of course “their working code is better than your imagined code” still applies, no matter how crap the code is. But looking for some kind of model in there could be rather futile.
(The fun part of playing with this kind code, if the circumstances allow, is that you can often reduce it to a fraction of it’s original volume and it still works… Which is also a good way of understanding what the code actually does, even if you don’t put the result back into production because god knows what little detail you might have overlooked or new bugs you’ve introduced along the way.)
October 23, 2009 at 11:34 am
You’re right about some devs not having a model; I oversimplified a bit. But you can’t protect against idiocy. A bigger problem is code that had multiple people work on it over time; you end needing to tease out multiple models.
Of course, when you make your changes you will add yet another model on top…
January 27, 2010 at 6:55 pm
“The fun part of playing with this kind code…is that you can often reduce it to a fraction of it’s original volume and it still works…”
That is true in a way as I had experienced that before. But there is a caution to this. Depending on how it was written, the “excess code” is there for optimization purposes or for specific client cases or both which you might not see due to your limited test cases or testing. Or it can be due to other portability reasons. Happened before.
January 28, 2010 at 12:14 pm
You’re right about that; you certainly have to fit the refactoring to the need. And never forget to respect the working code,right?
October 23, 2009 at 3:57 am
I was just today thinking that the greatest leap forward I made in my development career was when I got to the point where I could comfortably solve a problem by opening some project’s source code looking through it instead of hunting for the right tutorial online …
October 23, 2009 at 6:00 am
=== popurls.com === popular today…
yeah! this story has entered the popular today section on popurls.com…
October 23, 2009 at 7:57 am
Commonsense but needed to be said and you said it in the right way.
Thanks.
October 23, 2009 at 10:04 am
Any thoughts about tools for the job, e.g., code visualizers?
October 23, 2009 at 11:36 am
I’ve never found any that work on interestingly-complex real world codebase. Sadly.
Posted from #strangeloop!
October 23, 2009 at 11:09 am
The issue with understanding mental model of the code is that code decays over a period of time or the mental model gets skewed. I have run into situations where a certain section of code did not make sense to me. Removing/Refactoring the code however broke a section of code that is not related to the feature at hand.
Poorly written code becomes worst very quickly and copy-paste solutions become a norm. Feathers book on legacy code helps a little, but it is hard to pull the weight in an organization where code quality is valued by a select few.
October 23, 2009 at 11:27 am
Well said, Chris. It’s not only mandatory for changing existing code but also if you want to use modules or plugins for your current framework like Ruby on Rails, etc.
Especially in Rails, I’ve established the habit to read through most of the code of the plugins I want to use. For me it’s really important to understand exactly how they work and how they might affect our productive code. Monkeypatching in Ruby is a two-sided sword…
October 23, 2009 at 12:05 pm
You forgot to mention Version Control systems.
It’s helpful to review history of changes and differences between versions.
It’s also important to read code not only when code developer is gone, but also when s/he is present, but need your feedback on the changes that s/he just made in the code.
October 23, 2009 at 3:14 pm
[…] How to Read Other People’s Code — and Why Brillant! […]
October 23, 2009 at 8:25 pm
[…] How to Read Other People’s Code — and Why If you are a professional software developer, or aspire to be one, you will need to know a lot of of things. Various […] […]
October 24, 2009 at 3:37 am
What if we need the programmer to do an eloquent documentation? Pair program and put both to document, ask the supervisor(project lead etc) to check in only after that, and viola!! I was able to read a stored procedure’s documentation, find exactly the programmer was going wrong, and this in functional error, correct and get the results in an hours time!!
Document the code, programmers, document!!!!
October 24, 2009 at 8:06 am
[…] How to Read Other People’s Code — and Why […]
October 24, 2009 at 3:21 pm
Interesting. I’m now pondering whether there’s some taxonomy of mental modes that could help with the process of understanding Other People’s Code. For example I tend to cook up data structures and use them to drive the code. (Sometimes I end up overabstracting.) I find it hard to understand code that’s (IMHO) poorly abstracted or uses the “wrong” abstraction (i.e. not the one I’d have used); I wonder if people who write that sort of code would find mine to be overabstracted and hard to read.
October 24, 2009 at 10:59 pm
I’ve often wondered along these lines. Is there a set of core mental model types common across developers? If we could identify them, could we describe a mental model “lingua franca”, letting devs with different maps of the terrain talk to each other.
October 26, 2009 at 8:37 am
Very well said. Definitely agree with your remarks especially with not believing comments. Like you said, treat them as “archeological hints”. Definitely true. With all credit given to commenting, this is often the source of misinformation. People write and update code quickly forgetting to keep comments in sync, so they soon fall far behind.
“Don’t Hate the Code” is something that would present more obstacles. You can keep friendly with the code for as long as it is just different. When the code starts to interfere with your work and exposes all those hacks and tricks that were meant to solve an immediate problem without thinking about future maintenance, you won’t probably be able to help yourself. But you should of course try.
October 27, 2009 at 12:37 pm
I agree that not “Hating the Code” is really hard, but it is very necessary in lots of situations. Painful, but … like I said, working code in production has value all of its own.
October 28, 2009 at 12:03 am
[…] Design By Gravity Things work that way because the universe wants them to « How to Read Other People’s Code — and Why […]
October 28, 2009 at 12:33 pm
[…] a software practitioner, one of the coolest and most useful skills you can develop is that of reading other people’s code. It’s cool because it’s difficult, combining technical kung-fu with a rough-and-ready […]
November 3, 2009 at 11:26 am
[…] On the subject of reading code I recently came across an interesting post by designbygravity which describes some approaches for reading code more effectivel…. […]
November 12, 2009 at 9:19 am
em algumas semanas atras o meu not buki foi violada pois estavão abrindo o meu hotmail e olhando todas as minhas mensagens pois sol rosa cruz e vwem tudo comfidencial pois bem acabei não comseguino antrar maisno meu hotmail com o meu e-mail nen com a minha senha pois dizem que não esiteo por favor eu quero a minha senha de vouta não posso acessar mais nadanão temho nada a escomder mais quero a minha privacidade
porfavor me ajude pois fasso osmeus exrcisios pelo compoutadorgostari de saber se e pessoas do meu comvivio des de ja obrigado
November 12, 2009 at 10:24 am
como posso resolver o meu problema me diga por favor
gostaria de trocar o meu e-mail mais não queria perder tudo o que esta la me ajuda por favor mande a resposta para naritagiannini@hotmail.com pois ela e
minha filha muito obrigada por me ajudar vol esperar a res´posta do comtrario mandarei um emeio fora da minha residencia obrigado des deja
November 15, 2009 at 8:10 pm
Here’s a pickle for you:
You get code for a project that’s 60% done, but the quality is bad of the compiled code is bad. The source code, looks worse. Granted, it kinda works.
I strongly encourage writing things from scratch, since the people before you seem to have amateurs.
Would you agree?
December 18, 2009 at 6:50 pm
Tough call IMO as I have had to take over a number of code bases from previous programmers who clearly had less experience than myself, amateurs as you state. I’m not fan of rewriting code and a HUGE proponent of reading and understanding code first. That said if you are going to rewrite some functionality, not code, because you don’t rewrite code you rewrite functionality, then you had better FULLY understand the requirements of the piece of functionality.
This is the most difficult part of rewriting a piece of functionality because often people have forgotten how much a certain part of a system actually does. Those details are also often overlooked by the business persons who which to have a piece of functionality changed.
I still think you should avoid a rewrite whenever possible but if you do, get full buy in from the business or users of the software, to your new model for the functionality. The simple act of communicating will save you a lot of trouble. This is of course just my opinion based on my experience.
Oh and great article BTW!!
December 19, 2009 at 3:02 am
Good points there, KC. Most of time, I think we itch to rewrite code far too early — because it is the most fun. But for non-trivial codebases, you can really screw up.
The approach I usually take is to isolate a piece of functionality, refactor it so the rest of the system deals with it only through a new interface (at this point I’ve made no actual functional changes), make it creatable only through a factory.
Then, I can write a new replacement, and through the factory, switch back and forth until I am satisfied I got it right.
In practice, writing those initial interfaces and forcing the system to use them exclusively teaches me a lot about how the code is supposed to work.
YMMV
November 16, 2009 at 2:35 am
Good Post!
I worked on maintaining COBOL + .NET project. I am not proficient in COBOL but I know .NET and C# very well. Initially I suffered a lot understanding the COBOL code – as I don’t know the hacks in that language – though I can deduce what the original coder intended to do. So, I start off writing small algorithm for every function – activity. That way I could understand the part I need to work with thoroughly.
November 27, 2010 at 2:52 pm
Howdy! . Happy Thanksgiving! 🙂 🙂
Thanksgiving is 1 of my favorite holidays, and each yr I like to get into the mood-extend the holiday, when it were-by reading “Thanksgiving novels.” Not surprisingly, these stories are mostly about family and friends, about coming together to heal old hurts and giving thanks for the gift of love. . .. —
Think You’re Better Off These days Than You Had been three Years Ago?
June 20, 2011 at 10:35 am
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 20, 2011 at 12:58 pm
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 20, 2011 at 5:49 pm
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 20, 2011 at 6:24 pm
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 20, 2011 at 7:38 pm
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 20, 2011 at 7:41 pm
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 20, 2011 at 10:20 pm
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 20, 2011 at 11:05 pm
[…] âHow to Read Other Peopleâs Code, and Why,â Design by Gravity Overview of the key principles of reading code. […]
June 21, 2011 at 7:29 am
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 22, 2011 at 4:26 pm
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 23, 2011 at 10:03 am
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 29, 2011 at 5:36 am
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 30, 2011 at 2:32 am
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
June 18, 2012 at 8:49 pm
The problem with code reviews that I face is that sometimes team members don’t understand OO design concepts. When they design a class containing methods like “getProductData() // @return Gets product data.”, what am I supposed to say? I spend time explaining the concepts of OO design, then when they inevitably don’t understand (because if they did, they wouldn’t have done it that way to begin with), I spend loads more time getting intimately involved with their project in order to help them design it right. This is soul killing for me.
July 17, 2012 at 1:39 am
[…] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. […]
April 26, 2013 at 8:21 pm
Woah! I’m really enjoying the template/theme of this website. It’s simple, yet effective.
A lot of times it’s very hard to get that “perfect balance” between usability and visual appeal. I must say that you’ve done
a great job with this. Also, the blog loads extremely fast for me
on Opera. Outstanding Blog!
April 27, 2013 at 8:47 am
What’s Happening i’m new to this, I stumbled upon this I’ve discovered It absolutely helpful and it has helped me out loads. I am hoping to give a contribution & assist other customers like its helped me. Great job.
April 30, 2013 at 3:02 pm
forehead wrinkle treatment cream
May 3, 2013 at 12:44 am
body beauty anti-cellulite coffee
May 7, 2013 at 1:26 pm
However with a Wireless Router device you can be able to
protect your computing system and thus all your files are secured.
Your modem will also likely be connected to a wireless router and
it is this that allows your laptops, tablets, e-readers,
smartphones and other wireless enabled devices to be connected to the internet via your home broadband connection.
If you are unable to figure out the problem you should call wireless network support so that you
can browse the internet without any problems.
May 10, 2013 at 7:59 pm
bb – Press is made by Automattic, the people behind Word – Press.
Find out why so many online scammers don’t go to jail and see what con artists look like’all for
free with no registration required. Further, ask them to extend an invite to friends that might be
interested in joining the discussion.
May 11, 2013 at 1:22 pm
Soon after some time the digital technologies came into existence, wherein
the analogue signals are transmitted into digital ones and recorded onto a
Pc or laptop. 4 GHz device at your home go with a 900
MHz transmitter. Below are the most important things that must be done by you before
you can determine if this is the business you want to start.
May 14, 2013 at 10:04 pm
I do not even know how I ended up here, but I thought this post was good.
I don’t know who you are but certainly you’re going to a
famous blogger if you are not already 😉 Cheers!
May 31, 2013 at 1:09 pm
treat your own tennis elbow by jim johnson
June 1, 2013 at 10:13 pm
I’m curious to find out what blog platform you have been using? I’m having some small security issues with my latest website and I’d like to find something more safeguarded. Do you have any solutions?
June 29, 2013 at 7:45 am
Tribal tattoos are often blended with funky designs to lend
them a cool look. As you develop your own custom tattoo designs, you will discover the category that
you like most. Various people have a fixed aversion for them whereas other people love tattoos
designs.
July 22, 2013 at 8:53 pm
My partner and I absolutely love your blog and find many of your post’s to be precisely what I’m looking for.
Does one offer guest writers to write content for
you? I wouldn’t mind creating a post or elaborating on a lot of the subjects you write related to here. Again, awesome weblog!
July 27, 2013 at 6:30 pm
Oh my goodness! Incredible article dude! Thank you, However
I am experiencing issues with your RSS. I don’t understand the reason why I am unable to join it. Is there anybody having identical RSS problems? Anyone that knows the answer will you kindly respond? Thanx!!
September 7, 2013 at 11:04 am
I think the admin of this website is really working hard for his web page,
as here every stuff is quality based information.
September 13, 2013 at 5:05 pm
Greetings, I’m a greenhorn blogger and I enjoy reading this particular blog, so I thought perhaps I could receive
your guidance on something. Do you list everybody’s responses?
Even the ones that criticize and annoy you? I don’t know what to do.
September 17, 2013 at 3:06 pm
It is an inabiliity to transmit nerve impulses because compression has damaged nerve fibers either
directly, or indirectly by restricting their supply off oxygen.
Patients who are suuffering from blood clotting in their deep veins or
people with deep vein thrombosis should never be allowed to have a massage
therapy session as more and more complications will arise.
And sometimes cnildren whoo have Neuroblastoma Stage 4 cancers
will have to get a blood stem transplant.
March 15, 2014 at 2:00 pm
Парни если вам скучно то присоединяйтесь ко мне в скайп я очень люблю общаться в скайпе могу разговаривать на любую тему включая и интим))могу заниматься ЭТИМ вертуально ) так что если есть те кто меня поддержит в ЭТОМ пожалуйста жду в скайпе)все на бесплатной основе
Мой скайп: alino4ka1556
забыла сказать я часто бываю тут- w ww.sss777sss.ru
June 27, 2014 at 1:18 am
Hey there, I think your blog might be having browser compatibility issues.
When I look at your blog in Opera, it looks fine but when opening in Internet
Explorer, it has some overlapping. I just wanted to give you a
quick heads up! Other then that, terrific blog!
July 28, 2014 at 7:42 pm
To activate the singing, simply lift the light-activated sensor mug.
each and every single incident, right from the time the radio alarm went off and you got out of bed.
And so point there that I want to make is you got to be diligent in maintaining that
focus throughout the session.
August 18, 2014 at 6:29 am
Just wish to say your article is as astonishing. The clarity to your publish
is just spectacular and i can assume you are an expert in this subject.
Well along with your permission allow me to seize
your feed to keep updated with forthcoming post.
Thank you one million and please continue the rewarding work.
August 20, 2014 at 10:58 pm
Hi there, yes this article is truly nice and I have learned lot of things from
it concerning blogging. thanks.
September 4, 2014 at 7:07 am
I am regular reader, how are you everybody?
This article posted at this web page is really good.
October 6, 2014 at 8:39 pm
Hello colleagues, good paragraph and pleasant arguments commented
at this place, I am really enjoying by these.
November 28, 2014 at 6:53 am
Ι believe eveгything pօsted made а ton of sense. However, whyat about this?
what if you adԁed a little content? I am not suggestіng your іnformation іss not good.,
but sսppose yoս addеd a post title that grabbed people’s attention? I mean How too Reaad Othеr Peoples Code
– and Why | Design By Gravity is a little plain.
You ought tto glance аt Yahoо’s front page and see how they writе news headlines to get vieѡers to
open the links. Youu might add a video or a гelated pіc
or two to get гeaders injterested abоut what you’ve got to saʏ.
Just my opinion, it might bring your website a little livelier.
March 27, 2015 at 11:08 pm
I got this site from my pal who told me on the topic
of this web site and now this time I am visiting this web site and reading very informative content at this place.
December 7, 2015 at 3:52 am
Wow, marvelous weblog layout! How lengthy have you ever been blogging
for? you make blogging glance easy. The entire glance of your
website is wonderful, as neatly as the content material!
April 20, 2016 at 2:25 pm
[…] How to Read Other People’s Code — and Why […]
May 1, 2017 at 2:59 am
[…] How to Read Other People’s Code — and Why […]