wtd
|
Posted: Wed Aug 18, 2004 4:40 am Post subject: Programming for readability and maintainability |
|
|
Rule 1: Say What You Mean
This pretty much sums it up, and the rest are essentially specialized advice.
When you write source code, write it in such a way that it says what you mean. The whole reason for using pretty much anything other than machine code is the ability to create abstractions. Your source code, as much as possible, should convey what you're trying to accomplish, rather than how exactly you're accomplishing that goal.
Rule 2: Give Everything a Name
In order to accomplish rule 1, do not hesitate to give names to things. Hard-coded values are bad. In all likelihood, any given number (or other value) in your code has some purpose. Give it a name that indicates that purpose. You'll thank yourself when you have to back and figure out what a piece of code means.
Rule 3: Use Descriptive Names
As a corollary to rule 2, the names you give to variables should be descriptive. It should clearly denote what the variable is, or its purpose.
Rule 4: Avoid Lengthy Logic
Almost any single action or calculation in a program can be given a name. Use the facilities most languages provide to take advantage of this.
Creating functions or procedures that contain only a single line of code is not a sin. Rather it means your code will be more readable. No one will be wondering why you typed something like:
code: | (* in O'Caml, because I feel like it *)
Printf.printf "Sub-total: %f, Tip: %f, Total: %d\n" 15.0 (15.0 *. 0.15) (15.0 *. 1.15) |
If you don't type that, and instead replace it with something like:
code: | let calculate_tip tip_rate amount =
tip_rate *. amount
(* Partial application of the Printf.printf function *)
let print_receipt = Printf.printf "Sub-total: %f, Tip: %f, Total: %f\n"
let amount = 15.0 and tip_rate = 0.15 in
(* Partial application of the calculate_tax function *)
let calculate_dinner_tip = calculate_tip tip_rate
let tip = calculate_dinner_tip amount in
let total = amount +. tip in
print_receipt amount tip total |
And in C for those who get queasy at the thought of functional programming.
code: | int main()
{
printf("Sub-total: %f, Tip: %f, Total: %f\n", 15, .15, 15 * 1.15);
} |
vs.
code: | double calculate_tip(double tip_rate, double amount)
{
return tip_rate * amount;
}
void print_receipt(double amount, double tip, double total)
{
printf("Sub-total: %f, Tip: %f, Total: %f\n", amount, tip, total);
}
int main()
{
double amount = 15;
double tip_rate = .15;
double tip = calculate_tip(tip_rate, amount);
double total = amount + total;
print_receipt(amount, tip, total);
} |
Anything that can be a function/procedure/method/subroutine should be a separate function/procedure/method/subroutine. Take advantage of the language. Use it to your advantage.
Wrapping It Up
That's all for now. Feel free to post your own thoughts on the subject, and if you're wrong I'll just have to flame you to a crisp. |
|
|