码迷,mamicode.com
首页 > 其他好文 > 详细

学习good taste代码

时间:2017-05-14 22:51:29      阅读:338      评论:0      收藏:0      [点我收藏+]

标签:oid   表头   链表   不同的   address   linus   point   为什么   walk   

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代码

标签:oid   表头   链表   不同的   address   linus   point   为什么   walk   

原文地址:http://www.cnblogs.com/guochaoxxl/p/6854204.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!