zoukankan      html  css  js  c++  java
  • 学习good taste代码

    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 解释了一下新的代码,它消除了边缘情况,就是这样的。

  • 相关阅读:
    利用QObject反射实现jsonrpc
    使用libuv实现生产者和消费者模式
    std::function赋值的几种方法
    Qt postEvent
    Qt由pcm数据生成wav文件
    Qt websocket协议的实现
    Python中json.dump() 和 json.dumps()的区别
    Appium环境搭建(Mac)
    Mac上搭建Python集成环境
    Mac OS终端利器iTerm2(完美替代bash)
  • 原文地址:https://www.cnblogs.com/guochaoxxl/p/6854204.html
Copyright © 2011-2022 走看看