Slashdot Mirror


Ask Slashdot: How To Start Reading Other's Code?

BorgeStrand writes "I'm reviving an open source project and need to read up on a lot of existing code written by others. What are your tricks for quickly getting to grips with code written by others? The project is written in C++ using several APIs which are unknown to me. I know embedded C pretty well, so both the syntax, the APIs and the general functionality are things I wish to explore before I can contribute to the project."

39 of 254 comments (clear)

  1. Test and Break by jackyalcine · · Score: 4, Insightful

    If there's a lot of documentation, interpret it like your favorite religious text. Try to hit up some of the old developers from the VCS. Also, I'd like to help :)

    1. Re:Test and Break by Anonymous Coward · · Score: 3, Funny

      If there's a lot of documentation, interpret it like your favorite religious text. Try to hit up some of the old developers from the VCS.
      Also, I'd like to help :)

      The Great Programmer commanded his bytes to carry their bugs to the bitstream and drown them, or 7 years of seg faulting would follow.

      Join the Church of Emacs today!

    2. Re:Test and Break by ichthus · · Score: 5, Funny

      And lo, yea though ye shifteth right 8 bits, counteth not thy sign as verily carried henceforth unto the int8_t.

      --
      sig: sauer
    3. Re:Test and Break by mooingyak · · Score: 4, Informative

      Also, vowels apparently used to be very expensive in C variable names "back in the day."

      Certain early C implementations would only use the first 8 characters of a variable name. At that point, the vowels are usually the most expendable when coming up with names.

      --
      William of Ockham had no beard. The most likely explanation is that it was chewed off by squirrels every morning.
  2. Start with the headers by Beryllium+Sphere(tm) · · Score: 5, Insightful

    Knowing the data structures gives you the ground work for understanding what the code is doing. The data structures are a more direct description of the design decisions.

    1. Re:Start with the headers by girlintraining · · Score: 4, Insightful

      Knowing the data structures gives you the ground work for understanding what the code is doing. The data structures are a more direct description of the design decisions.

      This approach assumes the programmer hasn't gone native. Great for managed code, but when the data structures are basically pointers being passed back and forth and calls to APIs deep in the guts of the OS... well, how do I put this: You're screwed. It's a crap shoot on if the programmer even knows why it works... sometimes in C++ you stop debugging the moment it starts returning sane outputs and consider yourself lucky you didn't have to fully grok wtf just happened. :/

      --
      #fuckbeta #iamslashdot #dicemustdie
    2. Re:Start with the headers by inasity_rules · · Score: 3, Interesting

      I maintain a huge C++ codebase written by someone else. Pointers are no problem at all. The structures and classes they point to are all defined somewhere. The problem is, after loads of features tacked on randomly, the code has become unmaintainable. Core features break other core features and ugly hacks abound. Also Microsoft's OLE library breacks because the original coder did some extreme use case things that expose a long unfixed bug in modern OLE32.dll libraries. Working with code like this leads to the conclusion, that once understood, sometimes it is better to reimplement the whole thing building in all the core functionality from the base.

      This has been my practical experience with fairly well written C++ code. Comming from an embedded angle, there should be no problem understanding what the code does, or the data it works on, but maintaining or extending it may be a lost cause.

      --
      I have determined that my sig is indeterminate.
  3. How to read code by girlintraining · · Score: 5, Insightful

    What are your tricks for quickly getting to grips with code written by others?

    For me, it comes down to a lot of mountain dew, techno music, and hours of guru meditation. As you dissect each function, sketch out its relationship to other major functions. I take a two pass approach .. first, just look at the function call outs and the return values and make a rough sketch of the 'scaffolding' of a program. On the second pass, any function that you can't see the obvious application of, or appears obfusciated or complicated, dissect into functional units and sketch out what it does in your notes. I do this by actually physically drawing the relationships using something called a mind map.

    Until you get used to it, actually writing it down, even if it's just a bunch of messy arrows to blobs of circled text... it will help job your memory and help things sink in until you have the necessary 'ah ha!' moment.

    YMMV.

    --
    #fuckbeta #iamslashdot #dicemustdie
    1. Re:How to read code by cdp0 · · Score: 5, Informative

      Are there tools that do this automatically?

      Have a look at Scitools Understand.

    2. Re:How to read code by stephanruby · · Score: 3, Informative

      For me, if I can't understand code written by someone else (which happens much more frequently than I care to admit), I'll do a spike and I'll try to rewrite the core functionality from scratch. Now don't get me wrong. This doesn't mean that my code will be half as good as the original implementation, in fact, it won't be for sure, since I won't spend much time on it. For me, that exercise is just a way for me to initially orient myself (and I do not keep the code I write during that phase).

      If I'm lucky enough to have a good original version history of the code base, I'll go and pull up the original 0.1 version of the code (while I'm doing my own rewrite). Even if that version of the code is completely wrong. It still has a much higher chance of being something I'll understand. And then, I'll have a better understanding of what the developers were trying to do in the subsequent evolution of the project. Then, I'll isolate the parts of the latest code base I can safely break without breaking the entire thing, and I'll focus on those parts first.

      Of course, during that next phase, I'd like to say I write unit-tests for the parts I modify before I modify them, but that's usually not how I work. I'll often have to fall down flat on my face a couple of times, cry in pain and frustration, and tear my hair out, before I'm willing give up and go back to doing things properly with unit tests. This does happen quite frequently, because I never seem to learn my lesson.

      And of course, like someone else said already, I will also draw all kinds of mind maps and doodles throughout the entire process. And also, if I have access to one of the original developers who wrote the code, that's even better. If I can pair program with one of those persons, that's the ideal. If I can't, then talking to that person is the second best alternative. That person will be the best person to know all the weak points of his code base, give you a thumbnail overview of the architecture, and he will also be the best person to point out what parts you can work on first (so that you can gain confidence and a gradual understanding) that are the least likely to break the entire thing.

    3. Re:How to read code by ranton · · Score: 4, Insightful

      Honestly, I wouldn't get too comfortable with a given IDE -- some of them (I'm looking at you, Visual Studio) abstract away and hide a lot of the code and it can make for some really confusing times for you.

      Honestly, I would take more time to get comfortable with a given IDE so you can actually use it well instead of feebly. A good IDE like Visual Studio rarely abstracts away anything that you aren't trying to abstract away. And since most of the time you want almost every part of your program to be abstracted away from you, ,which is most of the power of a good IDE, this is what makes an IDE so useful.

      Not being competent with a good IDE is far worse than not completely grepping your coding environment at a low level. At least in today's world (I had a different opionion 15 years ago). Google and coworkers can fill in a lot of gaps in knowledge when necessary, but spending day in day out using an IDE and never realizing how much better it is than command line tools is a big waste of productivity.

      --
      -- All that is necessary for the triumph of evil is that good men do nothing. -- Edmund Burke
  4. Unit Tests by Anonymous Coward · · Score: 5, Informative

    If possible, I would try writing unit tests for the existing code. This tests your understanding of what you are reading and will come in handy later if you change the code. If unit tests already exist then I suggest that you read them since they will tell you the intention of each function.

    1. Re:Unit Tests by skids · · Score: 4, Insightful

      This. Looking at existing tests is also very educational. They often show where the codebase was confusing enough to cause recurring regressions.

      The other place to make very, very sure to read is the repository commit logs, if you have them. They'll tell you a lot about why the code is in its current state, and will often show you where refactors have been left half-complete.

    2. Re:Unit Tests by gd2shoe · · Score: 5, Insightful

      No, unit tests are a good idea. They wouldn't be my first choice, but they're a good option when deciphering a particularly difficult project.

      (1) It gets you to interact with the code. This is always a good idea when leaning how something behaves. Fiddle with it for a while and see if you can figure it out.

      (2) The unit tests don't need to be particularly true to their original requirements to be useful. When you do eventually start making changes, the law-of-unintended-consequences comes into play. If you make a change and one of your unit tests starts failing, then it will give you a clue that things may be interacting in a way that you did not anticipate.

      --
      I won't join Slashcott. OTOH, If Beta goes live, I just won't be back until it's fixed. Sorry Dice.
  5. Read someone elses Perl code first by jd2112 · · Score: 4, Funny

    Everything else will seem simple after that...

    --
    Any insufficiently advanced magic is indistinguishable from technology.
  6. Doxygen by mapinguari · · Score: 5, Informative

    Even without Doxygen's specific format for comments, you can use it to graph object relationships, call-trees, etc.

    You can generate docs limited to a few files or classes if you just want to focus on them.

    www.doxygen.org

  7. pretend you are the computer by Laxori666 · · Score: 3, Informative

    First, figure out how the code gets loaded and runs. Find the equivalent of the 'main' function. Then start tracing it, seeing what functions get called, how things are loaded, etc. What really helps here is an editor you can CTRL+click on a function on to go to its definition. When you hit a function that doesn't call any other unknown functions, then you can start understanding what it does without having to step into it. These are the basic functionality units. Then when you know enough of those, you can start going a level up, etc. Eventually a picture forms in your mind of just how things work. You can optionally skip over functions for preference of looking at them later if it seems pretty clear what they do based on the name & how they're called, but you might find important stuff in there later. This is how I go about it, anyway. It can be very frustrating and very confusing at first, but eventually the picture starts making sense, then things click in a most satisfying manner. That being said, the above is also the reason I can dislike complicated frameworks. There's so much indirection that it can take quite a while indeed until you hit something concrete. The mark of a good framework is, either it doesn't do that, or it does but soon enough you figure out its parts and then you can treat it intuitively.

  8. Reformat, Reformat, Reformat by zieroh · · Score: 4, Insightful

    I find that going through some key functions (assuming you can find them) and reformatting them to your own liking can be helpful, commenting code along the way. Then if you want to get more aggressive, start cleaning up some code in minor ways that still stay true to the function's meaning. After you've done a bit of that, you should probably have at least a vague idea what's going on.

    --
    People who say "sheeple" have about as much sophistication as an AOL user, and in fact are probably actually AOL users.
  9. Try some good quality marijuana by stevegee58 · · Score: 4, Funny

    It won't help you understand the code but you'll stop worrying about it so much.

  10. Bug hunting by tinkerghost · · Score: 3, Insightful

    I recommend starting by working on the bug list. It gives you something to work on constructively and it also makes you look through all the code to track the problem.

  11. Reading code is hard by benjfowler · · Score: 5, Insightful

    The trouble with university education, is that most people who teach there are computer scientists, not software engineers with years of experience in the trenches.

    If this were actually the case, there would be a recognition that reading code is far harder than writing it. And far more emphasis would be on coming to grips, understanding, and working on large code bases. There'd be more stuff on things like unit testing, breaking dependencies, troubleshooting, and refactoring at least.

    1. Re:Reading code is hard by Zalbik · · Score: 5, Insightful

      he trouble with university education, is that most people who teach there are computer scientists, not software engineers with years of experience in the trenches.

      Exactly. And it's why I always encourage programmers to write for readability rather than for terseness or whatever the latest cool tool is. Code is also read many more times that it is written.

      I'd much rather see a procedure that takes 10 lines is immediately obvious what it does than an "optimized" 5 line procedure that takes some head scratching to figure out.

      People who claim "more lines of code mean more probability of error" are typically very wrong. .

  12. Substances and coding by spasm · · Score: 4, Insightful

    Find out what drugs the original coder was using when writing, and take the same.

  13. Re: refactor, discard, repeat by Anonymous Coward · · Score: 5, Interesting

    Find a function. Refactor it until you grok it. Discard the results.

    Keep in mind that it will be VERY tempting to commit your changes, but you must throw away the work and chalk it up as a learning experience if you ever want to be taken seriously by the others who work on the project. Junior developers (and even some senior developers) often think they're doing everyone a favor by doing drive-by refactors, but they're not; they're just slowing down the entire team and coming across as that a**hole who keeps f***ing up the diffs and destroying the useful output of tools like git blame.

    If you found any bugs in the previous step, make a patch with the absolute minimal change to fix each individual bug. IMPORTANT: Before committing the patch, first be sure that you can reproduce it in the old code, and that the test case is fixed by your new code.

    Repeat the process until you understand the entire system.

    With any luck, you will finish with a solid understanding of how the code actually works, and you will most likely also fix a few dozen bugs (if you didn't find at least one bug per kLOC, then "you're doing it wrong" or the code was written by an inspired genius with OCD). At that point, you will be the team's expert on how things work, and you will be in a position where you can start proposing simple refactorings that will improve the code quality.

  14. C vs C++ by Rob+the+Bold · · Score: 4, Insightful

    You mentioned you have embedded C experience and the code of interest is written in C++. You didn't mention if you had any C++ or other object-oriented programming experience. I assume the C++ code uses the OO features of C++ that distinguish it from C -- but this assumption is not necessarily true.

    So, if you lack OO experience and the code is truly OO C++ code, you might want to do a little reading up on the basics of OOP in order to spend less time spinning your wheels.

    --
    I am not a crackpot.
  15. Rewrite some parts by eulernet · · Score: 5, Interesting

    Here is how I work on legacy code:

    1) I don't look at the whole picture because there are too much details, so I prefer to attack little by little.
    2) I quickly check what I can rewrite in order to optimize the code. If I have no idea, I run a profiler, and take a look at the routines that take the most time.
    3) once I understood or rewrote the most consuming parts (sometimes it's heavily optimized, but most of the time, I can make a real improvement), I decide what most important functionality I would like to add, and I just focus on that.
    4) if I really need to have robust code, I write tests for the routines before optimizing them, so that I can validate if there are regressions
    5) whenever possible, I use "assert" and put some bound-checking tests, in order to validate the ranges of certain values or conditions.

    The important thing is to start by taking ownership of a small part of the code, then a bigger part, etc...
    Take one slice at a time, not the whole pie.
    And one last point: knowing every little detail is useless, concentrate on what is important for you: performance, functionalities, ... ?

  16. Keep Some Rules In Mind by Greyfox · · Score: 5, Insightful
    1) Just because your predecessor was paid to program doesn't mean he craps daisies and unicorns. I have often gone in with the assumption that the guy before me knew what he was doing. Quite often I find I was wrong.

    2) Just because the code is awful doesn't mean it has no value -- No matter how bad it is and how difficult it is to read, if it works at all it has probably got years (maybe even decades) of bug fixes and feature requests. Until you have a handle on it, any little change could cause a catastrophic cascade of side-effects.

    3) No, we don't need to rewrite it. See 2. A working program now is worth more than all the pie in the sky you can promise a year from now.

    4) It takes 6 months to have a reasonably good grasp of any moderately complex in-house application. It could be a year before you get to the point where someone can describe a problem and you immediately have a good idea of where in the code the problem is occurring and what functions to check.

    Maintenance programming is as much about detective work as anything else. The only clues you have about the previous programmer are his source files. Once you've read them for a while you can start to tell what he was thinking, when he was confused, when he was in a hurry. Most of the atrocious in-house applications have changed hands several times and each programmer adds their own layer of crap. You can redesign these applications a chunk at a time until nothing remains of the original code if it's really bad, but it's best to save really ambitious projects until you understand the code better. I heartily encourage the wholesale replacement of "system()" calls with better code immediately, though. In several languages I've run across these calls to remove files, when they could have simply called a language library call (Typically "unlink".) If the original programmer used system("rm...") you can pretty much assume that they were a bad programmer and you're in for a lot of "fun" maintaining their code.

    --

    I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

  17. Since this is an OSS project ... by hedronist · · Score: 5, Interesting

    Since this is an OSS project, can you suggest any tools similar to Understand that don't cost $995?

    The only thing I could find was source navigator NG, but I have zero experience with it.

  18. Re:Use the tools Borge by drinkypoo · · Score: 3, Interesting

    Reading other people's code is a punishment that one must master if you hope to grow as a programmer.

    So what is the reward for reading comments which are unnecessarily set in monospace type?

    --
    "You're right," Fisheye says. "I should have set it on 'whip' or 'chop.'"
  19. CCVisu by PLAST · · Score: 3, Informative

    You can use doxygen to create a dependency graph and visualize it using CCVisu.

    http://www.stack.nl/~dimitri/doxygen/
    http://ccvisu.sosy-lab.org/
    http://ccvisu.sosy-lab.org/manual/main.html#sec:input-dox

  20. make it move by superwiz · · Score: 4, Insightful

    It's just how your brain works. It's a lot easier to examine a piece of mechanical machinery when it's in motion. You notice more. Do the same with the code. Run it. Run components independently. Put plenty of log statements or if it's feasible, watch under a debugger. But don't try to look at stale code just sitting there. You'll notice more as it moves.

    --
    Any guest worker system is indistinguishable from indentured servitude.
  21. Build it and run it by Java+Pimp · · Score: 3, Insightful

    You will never fully understand the code just by reading it. My approach is to ignore all of it until something needs to be changed. When you need to change something, add a feature, etc... find where in the code the functionality is and tweak it a bit. See what happens. Tweak it some more. See what breaks. You will start to get a deep understanding of a focused section of the code and not have to worry (yet) about other unrelated areas. Start with small changes first. Larger changes may require a deeper understanding of the architecture and how pieces interact. This will come in time. After a few iterations of this and you will eventually become intimately familiar with all the pieces of the code.

    --
    Ascalante: Your bride is over 3,000 years old.
    Kull: She told me she was 19!
  22. Re:Maybe. by Anonymous Coward · · Score: 3, Funny

    That's when you start reading tea leaves.

    Well, at least that's better than reading JavaBeans...

  23. Circle around for awhile. by shess · · Score: 3, Insightful

    Spend an afternoon or three skimming around the code pulling threads and following them. Jump around kind of randomly, if things start making sense in one module, go somewhere else for awhile. Take frequent breaks. Take notes about what you think things are doing, or perhaps ideas about how to improve the code - but don't start improving things now, you just want to figure out how much you're in for.

    After awhile doing that, you should have a few ideas about good accomplishable problems, now pick one and go deep for a limited time (hour, afternoon, week, depends on the scope of the code and your commitment to it). Again, keep notes, and then throw all your work away (or check it in somewhere - but don't focus on shipping, that detracts from learning). Again, go somewhere else in the code, fix something, take notes, throw it away. Alternate back and forth between research and application, trying not to bias towards one or the other (which can be a form of procrastination).

    Now throw away all your notes. They were written by someone who had no idea what was going on. By now you're pretty sure you know what's going on (you don't) and how to make things better (you have no idea), so circle around for another pass. Stop when you start finding that your notes seem to be recognizing actual immediately-actionable problems and solutions, rather than hypothesis and speculation. Or just stop because you're now so busy fixing things that you don't have time for exploration.

  24. Find the author by Antique+Geekmeister · · Score: 3, Insightful

    Find the person who wrote the code. Make sure that educating you or your colleagues is part of their paid responsibilities, and make sure that you respect their work when reviewing it: this helps them share the ir work and take it well if you need to revise things. My colleagues and I often bring new features or help stabilize old projects, and a working relationship with the original author is invaluable.

    And ff the author says "just read the code, I don't do documentation because documentation can lie", or if they say "don't bother checking the data for correctness, just don't make mistakes", be ready to throw out _everything_ they ever wrote. It may work at the moment, but it's likely to be as broken and unsustainable as their attitudes.

  25. hard to say by bloodhawk · · Score: 3, Funny

    I always find this greatly depends on the quality of the code, which varies greatly from well written and documented and just involves some boring reading and tracing through of execution paths too the absolutely appalling where you can sometimes only understand why the fuck they did something when you change the code and see how it breaks. The former I usually rely on a quiet room and lots of caffeine, the later requires swearing, loads of code changes to trace what is actually happening and cursing the original author, their relations and the goat you are sure they must have been molesting while writing the code.

  26. Re:Don't by mooingyak · · Score: 3, Interesting

    A person is a genius if he knows every nook and cranny of C++. But no one is expected to. Even just classes and objects are a fantastic addition over C, so there is really no reason to shun C++.

    The problem is that taking C and just adding classes and objects would have been nice, but the changes in C++ go so far beyond that they can reach a perl-like level of syntax confusion.

    --
    William of Ockham had no beard. The most likely explanation is that it was chewed off by squirrels every morning.
  27. Re:Maybe. by Endophage · · Score: 4, Informative

    There are plenty of design patterns other than MVC and depending on the particular application, MVC may not even be applicable.