Friday, August 22, 2014

Learning to Read Code

One of my junior co-workers asked me the other day for advice. They had inherited modules written by someone who'd recently left the company, & they were conflicted over whether to make drastic changes to the style & formatting, or just try harder to understand the code as it was so that the task at hand could be done.

   "How do you understand someone else's code without making it look like you're used to?"

Even if you have style guides, style checkers, automatic formatting, etc, there will be minor variations in style that can make code more in line with your own thinking, or small things that stand out as being "unreadable" that can taint the whole module. The classic examples are too much or too little comments, or too much or too little white-space. Note that these two, in particular, go both ways. It's a matter of personal preference.

No matter how much you work on Clean Code, a la Bob Martin, there will be tricks or approaches to a problem (even patterns) that you pick up in your career that are obvious to you, but will look strange & unreadable to someone else. Being aware that it might happen goes a long way to making your software more maintainable.

If you equate reading code to reading a book, for any given publishing market, the audience is essentially homogenous. As an author, you might aim for a geography & an age group (maybe a gender) or else a special interest. You more or less assume that anyone in that broad category will be able to read your book, & be able to understand what you have written - to appreciate it. The reality is that people always have favourite authors - a style or topics that they are more drawn to. Most people will also have authors that they just don't like - their style jars with them.

Reading someone else's code is exactly the same as reading a book that you didn't write. Some people write code that more people easily understand. Some write code that is targeted to a very specific niche audience - sometimes numbering one.

If you want your code to be maintainable, follow Uncle Bob's rules for Clean Code to get most of the way, but above all, remember that you are an author with an audience of coders who will read your work later.

If you want to approach other people's code to garner understanding - to maintain it - always remember that the author wasn't necessarily writing in your style, but you have to read it anyway, so look deeper for how they have gone about writing the code, how they are telling the story. The story is in there, because the code probably worked at some point. It is your job, as a maintainer, to find that story & understand it.

I can't teach you how, because I've achieved it through experience - voracious reading. There are no short-cuts to getting better at maintaining code. It just takes a lot more practice & a lot less wishing that the novel before you was as easy to comprehend as a Mills & Boone.

No comments:

Post a Comment