1. 程式人生 > >學習good taste代碼

學習good taste代碼

運用 情況 mov 既然 采訪 不同 val tor poi

Linux 的創始人,在采訪中提及了關於代碼的 “good taste”。Linus Torvalds 展示了一一些代碼:

void 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; } }

這是一個用 C 寫的函數,作用是刪除鏈表中的一個對象,它包含有 10 行代碼。主要在底部的 if 語句。正是這個 if 語句受到他的批判。 Linus 向觀眾解釋,正如我們所知道的,當從鏈表中刪除一個對象時,需要考慮兩種可能的情況。當所需刪除的對象位於鏈表的表頭時,刪除過程和位於鏈表中間的情況不同。這就是這個 if 語句具有 “poor taste” 的原因。但既然他承認考慮這兩種不同的情況是必要的,那為什麽像上面那樣寫如此糟糕呢?下面,Torvalds 展示了一一些代碼:他稱為good taste的代碼:

void remove_list_entry(entry){
    //The "indirect" pointer points to the *address* of 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; }

但代碼的行數並不重要,關鍵是 if 語句,它不見了,因為不再需要了。代碼已經被重構,不用管對象在列表中的位置,都可以運用同樣的操作把它刪除。Linus 解釋了一下新的代碼,它消除了邊緣情況,就是這樣的。

學習good taste代碼