2017/03/05

The mind behind Linux - Linus Torvalds


前一陣子在 TED 上看了這個訪談
不得不說 Linus Torvalds 可能是有部分工程師嚮往成為的一種典型
單純的喜歡寫程式
不擅也不樂於參與社交活動
其中談到了他對於程式碼的「品味」(taste)

"To me, the sign of people I really want to work with is that they have good taste, which is how ... I sent you this stupid example that is not relevant because it's too small. Good taste is much bigger than this. Good taste is about really seeing the big patterns and kind of instinctively knowing what's the right way to do things."

他所謂的 stupid example 是下面這兩個例子
從 linked list 中移除一個 entry
我覺得蠻有意思的
特別紀錄一下
他認為第二種寫法有比較好的 "taste"
remove_list_entry(entry)
{
    prev = NULL;
    walk = head;

    // Walk the list
    while (walk != entry) {
        prev = walk;
        walk = walk->next;
    }

    // Remove the entry by updating the
    // head or the previous entry
    if (!prev)
        head = entry->next;
    else
        prev->next = entry->next;
}
remove_list_entry(entry)
{
    // The "indirect" pointer points to the
    // *address* of the thing we'll update
    indirect = &head;

    // Walk the list, looking for the thing that
    // points to the entry we want to remove
    while ((*indirect) != entry)
        indirect = &(*indirect)->next;

    // .. and just remove it
    *indirect = entry->next;
}

"I don't want you understand why it doesn't have the if statement, but I want you to understand that sometimes you can see a problem in a different way and rewrite it so that a special case goes away and becomes the normal case."

試著用不同的方式詮釋一個解法
就可以將特例轉換成一般情況
讓我想起 circular array 中取得下一個 index 的寫法
有人可能會這樣寫
function getNextIndex(i)
{
    if (i >= n - 1)
        return 0;
    else
        return i + 1;
}
不過仔細想想其實用 mod 可以寫得更簡單
function getNextIndex(i)
{
    return (i + 1) % n;
}

不過他也說了
真正的 taste 是表現在更大的地方
會讓你覺得很直覺也很自然的設計
那就是好的 taste

沒有留言:

張貼留言