https://github.com/felipec/good-taste
An illustration of good taste in code
https://github.com/felipec/good-taste
Last synced: 3 months ago
JSON representation
An illustration of good taste in code
- Host: GitHub
- URL: https://github.com/felipec/good-taste
- Owner: felipec
- Created: 2022-02-06T03:55:41.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2024-08-02T05:14:46.000Z (almost 2 years ago)
- Last Synced: 2024-08-03T05:32:34.683Z (almost 2 years ago)
- Language: SCSS
- Homepage:
- Size: 56.6 KB
- Stars: 9
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
This is an explanation of how to write code with good taste by using a single
linked list example inspired by Mark Kirchner's project
[linked-list-good-taste], which in turn was inspired by a comment Linus
Torvalds made in his [TED talk][ted] in 2016.
In [part 1] we start by turning this typical implementation:
```c
void remove_list_entry(node **head, node *entry)
{
node *prev, *walk;
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;
}
```
into this:
```c
void remove_list_entry(node **head, node *entry)
{
node **p = head;
while (*p != entry)
p = &(*p)->next;
*p = entry->next;
}
```
In [part 2] we then explore how a real library (GLib) does it and improve it to:
```c
GSList *g_slist_remove_link(GSList *list, GSList *link)
{
GSList **p = &list;
while (*p) {
if (*p == link) {
*p = (*p)->next;
break;
}
p = &(*p)->next;
}
return list;
}
```
And finally in [part 3] we explore how Linux does it, and arrive to:
```c
void llist_del(struct llist_head *list, struct llist_node *entry)
{
struct llist_node *p;
llist_for_each(p, (struct llist_node *)list) {
if (p->next != entry) continue;
p->next = entry->next;
return;
}
}
```
Which is vastly superior, and in good taste.
[linked-list-good-taste]: https://github.com/mkirchner/linked-list-good-taste
[ted]: https://youtu.be/o8NPllzkFhE?t=858
[part 1]: https://felipec.github.io/good-taste/parts/1.html
[part 2]: https://felipec.github.io/good-taste/parts/2.html
[part 3]: https://felipec.github.io/good-taste/parts/3.html