Linus的代码品味之一


       Example of bad taset

  1. remove_list_entry(entry)  
  2. {  
  3.     prev = NULL;  
  4.     walk = head;  
  5.     
  6.   
  7.     // walk the list
  8.     while (walk != entry){  
  9.         pre = walk;  
  10.         walk = walk->next;  
  11.     }  
  12.   
  13.     // Remove the entry by updating the
  14.     // head or the previous entry 
  1.     if (!prev)  
  2.         head = entry->next;   // the case of entry is head element
  3.     else  
  4.         prev->next = entry;   // normal case
  5. }  


    Example of good taste

    

  1. remove_list_entry(entry)  
  2. {  
  3.     // The "indirect" pointer points to the
  4.     // *address* of the thing we'll update

  5.     indirect = &head;  

  6.     // walk the list, looking for the thing that
  7.     // points to the entry we want to remove  
  8.     while ((*indirect) != entry)  
  9.           indirect = &(*indirect)->next;  
  10.     // .. and just remove it 
  11.     *indirect = entry->next;  
  12. }  


      这个例子中的核心思想是把特殊Case作为初始值,进而消除后续流程中对特殊Case的处理过程。实现简洁的代码设计。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值