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

posted @   叕叒双又  阅读(512)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示