Rabu, 03 Maret 2010

On reading code

Last week I started using github, forked a project, and read some of miyagawa's beautiful code. Later on the weekend, I imitated a particular style I found from his code to improve my own code.

And then I realized: during the course of many years as a programmer, I really really seldom read other people's code, especially real-world code. Sure, I do whenever I have to patch something. But other than that, practically never.

Other than code, I do read an awful lot: books, magazines, mailing lists, forums, blogs, web pages. I have never doubted the benefits of reading for improving knowledge and understanding, so why haven't I read more code? A couple of reasons I can think of:

1. We programmers are not paid to read code. We are paid to write programs, to churn out lines upon lines of code. Heck, we're not even paid to write good code, we're paid to get the job done.

2. Reading code is hard. It can really drain your brain. Imagine a recipe book where the flow of instructions is not linear (jump to line X, jump to page Y and then return here), where a misplaced character can destroy the whole recipe, and where everything is so interdependent and interlinked that you need to read everything twice first before you can begin to understand it.

3. Reading code is boring. Can you really curl up with a good program the way you can with an exciting novel?

4. Reading code is not necessary. A good reusable piece of code need not be read anyway, all you need is its API documentation. Programmers are hired regardless of their ability to read real-world code, there are no interview tests in reading code other than a few or at most a dozen lines of it. Heck, programmers are even hired despite their inability to write any code at all.

After experiencing that one session of code reading can do some wonders, I'll make it a program to read more (good) other people's code.

2 komentar:

  1. So which style was it you found yourself inspired by and imitated?

  2. @asjo (copy-pasted from my comment to the same post in blogs.perl.org):

    There are actually a few, e.g.:

    1. The use of dialect (or DSL?), encountered a lot in Ruby, like using:

    hook 'name', sub { ... };

    instead of:

    sub hook_name { ... }

    apparently one of my projects could benefit from the added clarity especially because it has lots of "special types" of subroutines/handlers.

    2. More attention to column length and subroutine length. More attention to "beauty". I've noticed that my code tends to be ugly :)


Catatan: Hanya anggota dari blog ini yang dapat mengirim komentar.