7 ms·
How to Read Other People's Code -- And Why
- pgbovine 17y agoone technique i often use when trying to understand someone else's code is to add in comments myself in my private branch (of the form "I think that X works like Y and Z"), or even better, adding in run-time asserts that I think ought to hold, and then running tests to make sure they do hold. Of course, i never check in my comments/asserts to the main branch, since i'm not sure whether my understanding is correct
- JoeAltmaier 17y agoCode management tools need a way to add notations without getting in the way of code. Something that can be view thru a link, but is out of the way when poring over the code. ASCII text: anachronism. We're not that far from 80-column IBM punched cards...
- omouse 17y agoYou want something like literate programming then
- diN0bot 17y agoif the original code writers had used comments and asserts to not only assert their assumptions but then maintain those assumptions over time, then you wouldn't have to. plus, they'll probably introduce less bugs and debug faster in the future. i can only speak from my own experience, thought processes and developing skillset. everyone's different. some people can keep track of numerous complex relationships in their head for months on end.
- deleted 17y ago[deleted]
- ivenkys 17y agoI do exactly the same. Added to this, in large legacy code bases with no or very little tests, i sometimes try and break the functionality near to the part where a new fix is required in my private branch to check my understanding. I find that its much easier to understand the code when something doesn't work rather than when its working perfectly. With any luck, the stacktrace will tell me what's going on.
- pmjordan 17y agoOf course, i never check in my comments/asserts to the main branch, since i'm not sure whether my understanding is correct I also add my own comments when understanding/using/changing other people's code. I do eventually check them in though. After all, why not? * If the original author is no longer available, you're now the best authority on the subject; chances are your comments will help anyone in your shoes sometime later, including yourself. If you're really unsure, add that information to the comments. * If you're making changes based on your understanding of the code, you or someone else will be testing those changes, thereby validating or falsifying those assumptions. If, after testing, the bugfix/feature/task works, so do the comments. * If the original author will be available at a future date, you can get them to do a "comment review" (cf code review) when they get back.
- stavrianos 17y agoif it's unclear enough what the code does that you need to do this, maybe some speculative commenting in the main branch actually would be an improving.
- abstractwater 17y agoonce you determine your understanding is correct (there are a number of ways to make sure of it, like asking the author when he becomes available), I think you provide a service if you abridge your comments and check them in. Sometimes it's like fixing a "incomprehensible code" bug.
- sophacles 17y agoOn the how bit: there is no such thing as reading code once. It is a simple matter of reading a method/object/what-have-you, then rereading it until you see it called/referenced etc and don't ask yourself "wtf does foo do". Trace various code paths often enough and you'll 'get it'. As for the why: I used to decide I didn't like module X, then decide I was going to implement it myself. After some time I would end up with something looking like X, but not nearly as refined. As such, I learned it's better to read others' code and understand it -- much faster than reaching the same conclusions as the original authors w/ crappier code. Of course if after understanding you decide you still think it's crap -- have at it :).
- wakeless 17y agoI don't mind using code folding when I'm doing this. Trying to fold the code down that I don't care about, this way there isn't as much to read and get lost in.
- simplegeek 17y agoAlso, using a debugger (if it can be used) can be really helpful
- Mongoose 17y agoRead the comments, but don’t believe them Love that one. A grad student friend I work with, whenever he catches me poring over documentation, always tells me to read the code. Such a seemingly simple tip, but so valuable.
- notthinking 17y agoIt might be my relative newness to software, but I enjoy looking at other peoples code to see what works (pick up new language features) and what doesnt.
- Aschwin 17y agoOne of the reasons I don't write comments is because it gets outdated so quickly. And I don't need them myself, because I read only the code, even my own. Reading the code makes also for reviewing the code. Quickly changing bits so it makes better sense (like counts outside the for-loop instead of in the statement) etc. And use version-control system to make changes, test them and roll it back (revert). TortoiseSVN helps a lot with this for me. I also try to make the code more readable by adding my codingstyle or the codingstyle by convention (I still think mine is best ;-)
- notauser 17y agoIf top-of-function comments like: /* Does everything required to initialise the UI (DO NOT CALL DIRECTLY - see class foo) */ Get outdated quickly (without being updated) you have big problems. Equally a one line comment before things like: // Do this if we can be certain we are in month X if (!(!x || ($chk(diff(y,o)) && (z<p))) {...} Saves you having to draw out a truth table each time. Even if the logic gets tweaked a bit when bugs are found the purpose of the code is likely to remain and so the comment won't age too badly.
- derefr 17y agoIn the first case, perhaps the function should only be accessible by/from Foo, or those that share a Foo-ish interface. In the second, I would really hope to be able to abstract that into a call to s.in_month?(m), with s perhaps being built from some combination of $chk, x, y, o, z, and p.
- olliesaunders 17y agoYour parenthesis don't even match in the second example, which could easily be re-written not to require a comment by renaming the variables.
- bendtheblock 17y agoWhen I was studying CS, one of the things I was told was that if you grep and get only the comments out of a particular file/class, you should effectively see the pseudo-code of the program. In reality, I comment very little, just pointing things out that can’t be quickly deduced from casually reading the code.
- axod 17y agoI'd also heartily recommend learning to read other peoples code from the assembly - softice/dissassembly listing.
- jcl 17y agoCould you elaborate? It doesn't sound like it would improve your understanding of the code.
- wenbert 17y agoMaybe it's just me. But sometimes I draw diagrams describing how the code will work and how the methods interact with each other. A quick drawing with a pencil and paper or on a whiteboard will do. It helps me understand how the over-all system works...
- JoeAltmaier 17y agoAgreed. If it won't all fit in my head at first, put some of it on paper. Especially when learning the code. And re-visit the drawing, testing it against what I'm reading as I go until I'm sure its right. Once its in my head, throw it away. Wish there was some way to use drawings as comments... My friend Bob learns differently - he needs words, skips all the illustrations in manuals, they just don't sink in for him. He's brilliant, just built differently.
- wenbert 17y agoThat'd be the day :D Drawings for comments is absolutely a great idea. Sometimes I wish I could "draw" something in my code (Arrows, bookmarks, quick diagrams, etc. beside comments). Think github with this kind of feature.
- olliesaunders 17y agoMichael Feathers' Working Effectively with Legacy Code is the authority on this, I think.
- silentbicycle 17y agoNot quite - it's primarily focused on safely retrofitting unit testing onto legacy codebases, since restructuring code to make it testable can easily break it. His definition of legacy code is code that doesn't have tests, so you can't fix it or replace units of it without unknowingly introducing bugs.
- deleted 17y ago[deleted]
- alexkearns 17y agoI don't know about the rest of you but I got into software development to create software (ideally from scratch) and to learn clever new stuff, not to tinker with someone else's code. Of course, just like every other software developer, I have on occasions ended up working in someone else's codebase. But I have done this not out of choice - and except in a handful of cases, I have not gained any knowledge or mental satisfaction from doing so. I have done it because I have been told to by my boss. Let's not con ourselves. Becoming a dab hand at maintaining other people's software does not make you a good software developer (writing your own software does that). It makes you a good employee who is willing to do the boring shit. The two are not the same. I for one hate maintaining other people's code, and if I ended up doing that the majority of the time, I would either get a new job, switch careers or kill myself. Probably one of the first two.
- axod 17y agoI think you're missing the point. The idea isn't to have to maintain someone elses rubbish code. The idea is that reading good code makes you a better coder. Which it certainly does. Having said that, bad code can sometimes teach you lessons in how not to do things. Good authors probably read other books as well.
- jcl 17y agoAt some point in your career, you come to realize that unreadable code is bad code -- and that if you aren't writing readable code, you are a bad coder. Usually this realization comes when you are asked to fix something in code so horrible that it causes you to wonder aloud, "What idiot wrote this?" And you look in the repository logs and see that it was you, several months ago. Even if you never intend to maintain code, if you don't want to be that guy whose code everyone hates to work on -- whether out of compassion for your maintainers or out of career self-interest -- you need to know how readable your code is relative to others'. And the only way to know this is to read other people's code.
- known 17y agoOne productive technique to read other people's code is to step into the code using a debugger (e.g. gdb)
- kls 17y agoI agree, the debugger is so important to understanding foreign code, yet so many people only use it when they are looking for a bug or not at all.
- tetha 17y agoI disagree with this. The debugger is a very, very precise tool and it can be used to gain very, very precise insights into certain code, however, very often the debugger is just too precise. It is pretty much like trying to understand a large chip by looking at how gates flip and flop. Of course, if the code is horrible enough, then you might need to switch down to actually tracing line by line and opcode by opcode, potentially even using a debugger, but for most sane code, I think it is possible and faster to understand larger blobs of code at once.
- bendotc 17y agoAgreed. In general, if you're having trouble tracing through a particular function with a narrow band of input, then the debugger can be useful. If you're trying to figure out a larger system and/or how a system works across a large set of inputs, then stepping through with a debugger is useless. Put another way, the debugger is to programming what the microscope is to medicine: incredibly useful for some things, but not a very good general diagnostic tool. Metrics data and checking assumptions (via unittest and/or asserting expectations based on reading the code) are much better for getting an over-all idea of what's going on. Once you've localized a problem, then the debugger can help you get a precise idea of the issue, or can help you test a hypothesis (to use the medical example, you can use the microscope to test a theory that there's a bacterial infection).
- AGorilla 17y agoNot to mention the side effects of breaking code you don't understand at random points.
- jmostert2 17y agoIf the code is really intricate, I refactor it to understand how it works (and how it ought to work, which can be an important way of spotting bugs). But even though refactoring is supposed to be perfectly mechanical and "harmless" (especially when supported with unit tests) I'll usually throw away my refactoring, because the risk of breaking the existing code is just too high. It depends on how invasive the new feature is -- if I'm going to have to change a lot to get it done anyway, I might as well incorporate the refactorings. But if the change literally is finding the right position to add a single line of code, no way I'm going to change things once I find it. When it's clear that adding even simple features takes an extraordinary amount of time because the code is that hard to understand and maintain, getting/making time for proper refactoring is easier, but it's worthwhile even as a way of creating a mental model. I've never tried unit tests to figure out the semantics of existing code, though, even if it seems obvious in retrospect. I think the code base would have to become very complicated indeed before I go into full scientist mode and construct hypotheses on the semantics and verify them with unit tests. If the code is a tangled mess, it could also be tough to extract the proper bits to test on and/or set up a test environment complete enough for that.
- berntb 17y agoI quite liked this, regarding this subject: http://perlmonks.org/?node_id=788328 http://perlmonks.org/?node_id=788328