[读书笔记] "The Practice of Programming" 程序设计实践

我不会 C++ 或 Java, 所以书中的例子将用 rust 来改写.

1.代码风格.

常量的不应该这样命名, 会导致难以修改它的值:

//bad
const ONE: u8 = 1;
const TEN: u8 = 10;
const TWENTY: u8 = 20;

常量的命名应当要表现其作用:

const INPUT: u8 = 1;
const INPUT_BUFSIZE: u8 = 10;
const OUTPUT_BUFSIZE: u8 = 20; 

全局的命名应当是描述性的, 以说明其在程序中的作用. 简短的注释也很有帮助:

let npending = 0; // current length of input queue

而本地(局部)的命名应当简短, 比如以下代码:

//bad
for theElementIndex in 0..numberOfElements {
    elementArray[theElementIndex] = theElementIndex;
}

应当简化成:

for i in 0..nelems {
    elem[i] = i;
}

命名应该保持连续. 以下代码就是个坏例子:

//bad
    struct UserQueue {
        noOfItemsInQ: u16,
        frontOfTheQueue: u16,
        queueCapacity: u16,
    }

    impl UserQueue {
        pub fn noOfUsersInQueue() {...}
    }

"queue" 分别以 Q, Queue 和 queue 三种形式出现. 而且作为 UserQueue 结构体中的变量, 不需要再提到 "queue" 了. 下面的代码就更好一些:

    struct UserQueue {
        nitems: u16,
        front: u16,
        capacity: u16,
    }

    impl UserQueue {
        pub fn nusers() {...}
    }

函数名应该使用动作短语. 返回值是 bool 的函数应当以判断短语命名. 函数的命名应当与其功能相匹配.


使用缩进让结构更清晰. 在表达式中使用更自然的形式. 使用括号来避免歧义. 把复杂的表达式分解开.


代码要简介清晰. 请看这行代码:

//bad
subkey = subkey >> (bitoff - ((bitoff >> 3) << 3));

它现将 bitoff 右移3位, 然后左移3位, 得到 bitoff 最后3个 bits 变为0 的数. 在用 bitoff 减去这个数, 得到 bitoff 的最后3位 bits. 最后把这三个 bits 作为 subkey 右移的量. 这段代码等同于:

subkey = subkey >> (bitoff & 0x7);

或者还可以更简短:

subkey >>= bitoff & 0x7;

练习: 改善以下代码:

//bad
if ( !(c == 'y' || c == 'Y') ) {}
if (c != 'y' && c != 'Y') {}

使用一贯的缩进和括号风格. 使用约定俗成的用法.


在多路决策时使用 else-if 或 match 结构.


魔法数字是指程序中的常量, 数组大小, 字符坐标等等的数字值.
为了便于理解, 程序中的魔法数字应当有合适的命名. 不要使用明确的数字来表示任何数据类型的 size, 而应该使用计算size或length的函数.


不要啰嗦那些显而易见的事. 要为函数和全局数据添加注释. 不要注释差劲的代码, 而应该重写它们.

2 算法与数据结构

搜索算法.

对于较少的数据, 顺序搜索就够用了(感谢 tennix 告诉我如何表示字符串数组的类型):

    let flab = ["actually", "just", "quite", "really"];

    // lookup: sequential search for word in array
    fn lookup(word: &str, array: &[&str]) -> Option<usize> {
        for i in 0..array.len() {
            if word.cmp(array[i]) == std::cmp::Ordering::Equal {
                return Some(i);
            }
        }
        return None;
    }
    println!("{:?}", lookup("just", &flab));

对于体积巨大的数组, 就适合使用二分法搜索(需要先经过排序):

    use std::cmp::Ordering;

    struct Nameval {
        name: &'static str,
        value: u32,
    }
    // HTML characters, e.g. AElig is ligature of A and E.
    // Values are Unicode/ISO10646 encoding.
    let htmlchars = [
        Nameval {name: "Aelig",  value: 0x00c6},
        Nameval {name: "Aacute", value: 0x00c1},
        Nameval {name: "Acirc",  value: 0x00c2},
        // ...
        Nameval {name: "zeta",   value: 0x03b6},
    ];

    // lookup: binary search for name in tab; return index
    fn lookup(name: &str, tab: &[Nameval], ntab: usize) -> Option<usize> {
        let mut low = 0;
        let mut high = ntab - 1;
        let mut mid;
        let mut cmp;
        while low <= high {
            mid = (low + high) /2;
            cmp = name.cmp(tab[mid].name);
            match cmp {
                Ordering::Less => high = mid - 1,
                Ordering::Greater => low = mid + 1,
                _ => return Some(mid),
            }
        }
        None
    }

排序

评论

暂无评论