Bug-free development: Source code readability
- 2012年04月26日
Source code readability is important. Even nobody else will read your source code in the future, you will read it one day. Dirty code provides good shield for bugs for they become harder to find. Dirty code may also mislead other programmers to think they find a bug, and by “fixing” it, they create a real bug.
Indention
One good reason I like Python is, no matter the programmer is amateur or professional, at the first glance, the source code is so clean. If the source code is not properly indented, then it may not run at all. Well-indented source code helps the reading speed, and makes the bugs easy to reveal.
There are many code beautifiers that standardize the code style. For example, in UNIX there is a command called “cb” (C Beautifier), and in Visual Studio, there are shortcuts standardizing the code format as well. When I programmed in C, I always ran the “cb” command and compared the output with my source code, and made sure no differences were found between the two. Call me obsession, but once I got used to it, it became very natural to write well formatted code at typing.
Explicitness
Being explicit means, for example, if part of the code is supposed to do nothing, then, instead of writing nothing, do put some code or comments to speak out: “I am here to tell you, nothing should be done. I did not forget to consider this case.”
Here is an alarm clock program. It used to work before but is not working now. Instead of triggering the alarm by the desired time, it does the inverse logic – keep ringing the alarm until the time is reached. The investigation shows that the latest version is like this:
for (time() < desiredTime)
puts(“wake up”);
Then no surprise why it keeps sending the alarm. Why the code is like this? One week ago Susan read the code and discovered that the code was like:
for (time() < desiredTime);
puts(“wake up”);
and she thought that the “;” at the end of the “for” statement was a typo, so she removed the “;” wrongly, and this “fix” ultimately reserved the logic.
To avoid this misunderstanding, Mike, the author of the previous version, should have written his code as below, so if Susan saw this code, she would have been thought twice, or picked up her phone to quickly confirm with Mike, before applying the “typo correction”.
for (time() < desiredTime)
;
puts(“wake up!”);
A even more explicit code is like this. The “NULL” statement does not generate any extra code, but it explicitly tells the audience “I mean to do nothing here.”
for (time() < desiredTime)
NULL;
puts(“wake up!”);
Other examples: The NULL statement in the “else” block makes explicit that no actions should be taken if neither A nor B is met. The “fall through” comment in the “switch” block makes explicit that the “break” statement is not forgotten here, but the programmer intends to execute do_this() and do_that() when a equals to 0.
猛击阅读全文