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: Tech

Tags: , ,

You can comment below, or link to this permanent URL from your own site.

69 Comments on “How to Read Other People’s Code — and Why”

  1. wenbert Says:

    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! ;)

  2. Kaz Chehresa Says:

    “…archeological hints” classic. I gotta use that!

  3. Rick Says:

    “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.)

    • designbygravity Says:

      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…

    • Ben Says:

      “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.

      • designbygravity Says:

        You’re right about that; you certainly have to fit the refactoring to the need. And never forget to respect the working code,right?


  4. 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 …


  5. === popurls.com === popular today…

    yeah! this story has entered the popular today section on popurls.com…

  6. Venkatesh Sellappa Says:

    Commonsense but needed to be said and you said it in the right way.
    Thanks.

  7. sedwards Says:

    Any thoughts about tools for the job, e.g., code visualizers?

    • designbygravity Says:

      I’ve never found any that work on interestingly-complex real world codebase. Sadly.

      Posted from #strangeloop!

  8. Ravi Says:

    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.

  9. webops Says:

    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…


  10. 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.


  11. [...] How to Read Other People’s Code — and Why Brillant! [...]


  12. [...] 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 [...] [...]

  13. Arun Says:

    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!!!!


  14. [...] How to Read Other People’s Code — and Why [...]

  15. Rick Innis Says:

    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.

    • designbygravity Says:

      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.


  16. 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.

    • designbygravity Says:

      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.


  17. [...] Design By Gravity Things work that way because the universe wants them to « How to Read Other People’s Code — and Why [...]


  18. [...] 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 [...]


  19. [...] On the subject of reading code I recently came across an interesting post by designbygravity which describes some approaches for reading code more effectivel…. [...]


  20. 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


  21. 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


  22. 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?

    • KC Says:

      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!!

      • designbygravity Says:

        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

  23. Srikanth Says:

    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.

  24. Dori Says:

    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?


  25. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  26. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  27. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  28. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  29. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  30. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  31. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  32. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  33. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  34. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  35. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  36. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]


  37. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]

  38. Ezekiel Says:

    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.


  39. [...] “How to Read Other People’s Code, and Why,” Design by Gravity Overview of the key principles of reading code. [...]

  40. vision Says:

    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!


  41. 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.


  42. forehead wrinkle treatment cream


  43. body beauty anti-cellulite coffee

  44. Wifi Cracker Says:

    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.

  45. Mickey Says:

    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.


  46. 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.


  47. 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!


  48. treat your own tennis elbow by jim johnson


  49. 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?

  50. tattoo Says:

    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.

  51. Kaminomoto Says:

    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!

  52. Sandra Says:

    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!!


  53. I think the admin of this website is really working hard for his web page,
    as here every stuff is quality based information.


  54. 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.

  55. Nikole Says:

    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.

  56. Melissacaf Says:

    Парни если вам скучно то присоединяйтесь ко мне в скайп я очень люблю общаться в скайпе могу разговаривать на любую тему включая и интим))могу заниматься ЭТИМ вертуально ) так что если есть те кто меня поддержит в ЭТОМ пожалуйста жду в скайпе)все на бесплатной основе
    Мой скайп: alino4ka1556

    забыла сказать я часто бываю тут- w ww.sss777sss.ru


  57. 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!

  58. Lucas Says:

    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.


  59. 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.


  60. Hi there, yes this article is truly nice and I have learned lot of things from
    it concerning blogging. thanks.


  61. I am regular reader, how are you everybody?
    This article posted at this web page is really good.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: