Example of bad taset
- remove_list_entry(entry)
- {
- prev = NULL;
- walk = head;
- // walk the list
- while (walk != entry){
- pre = walk;
- walk = walk->next;
- }
- // Remove the entry by updating the
- // head or the previous entry
- if (!prev)
- head = entry->next; // the case of entry is head element
- else
- prev->next = entry; // normal case
- }
Example of good taste
- 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;
- }
这个例子中的核心思想是把特殊Case作为初始值,进而消除后续流程中对特殊Case的处理过程。实现简洁的代码设计。