remove_list_entry

学习如何写有品味的代码

remove_list_entry(无需 if 逻辑)

  这是期TED里面的内容,内容是采访linux的之父Linus Torvalds。
  Linus Torvalds两次改变了技术,第一次是Linux内核,它帮助互联网的发展,第二次是Git,全球开发者使用的源代码管理系统。在一次TED的采访中,Torvalds以极其开放的态度讨论了他独特的工作方式和性格特点。Torvalds说:“我不是一个空想家,我是一名工程师,我非常乐意跟梦想家在一起,他们行走四方,仰望苍穹,看着满天星辰说,“我想到那儿去。”但我是低头看路的那种人,我只想填好眼前这个坑,不让自己掉进去,这就是我。” ***

  在聊天中CA问道了一个关于代码品味的的问题,这个问题其实很有意思,对于很多写代码的人来说,有好的代码风格和代码品味就好比有了一种审美品味一样。就好比在写代码时你的缩进习惯一样。

第一段代码

remove_list_entry(entry)
{
    prev = NULL;
    walk = head;
​
    // Walk the listwhile (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;
}
这里我注释一下哈,这两段代码都是伪码。所以看起来有点奇怪

  看起来这两段代码功能上都一样的但是,第一段的最后用了一个if和一个else目的在于处理特殊情况,但是第二段代码很简洁没有if和else来处理特殊情况,这是一种很有意思且巧妙的思想同样Dummy Node链表也是一种处理方式,在这里不讨论,后面我回专门来说这种链表。

Node *head, *prev, *walk;
void remove_list_entry(Node* entry)
{
    prev = NULL;

    // walk 这一变量名,十分巧妙,
    // 变量命名的不二法门就是对应其物理(实际)意义
    walk = head;

    while (walk != entry)
    {
        prev = walk;
        walk = walk->next;
    }

    // 也即没有执行 while 循环,walk == entry,entry == head
    if (!prev)
        head = entry->next;
    else
        prev->next = entry->next;

}
void remove_list_entry(Node* entry)
{
    Node **indirect;
    indirect = &head;
    while ((*indirect) != entry)
        indirect = &(*indirect)->next;
    *indirect = entry->next;
}

  这是两段代码的表准形式

  为什么要区分是头指针呢,因为整个程序的逻辑是找到被删除指针的前一个指针,如果被删除的指针为头指针,显然其没有前一个指针。 显然这种的代码不具很好的 taste,话说 Jobs 也很爱讲 taste(Windows 最大的特点就是 has no taste)。这两段代码的显著区别就是第二段代码省略了 if 语句,对头指针和前一个指针做了统一化处理。 头指针没有前一个指针,但有自己的地址,自己的地址自然还是指向自己。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!