官术网_书友最值得收藏!

1.2.2 妙手理碼

拿到壞代碼時(shí),一個(gè)很好的習(xí)慣就是對(duì)代碼按照編碼規(guī)范的要求進(jìn)行整理。這一過程本身就是閱讀代碼的過程,通過整理,我們可以使代碼變得更加清晰易懂,也可能發(fā)現(xiàn)并解決一些潛在的問題。

程序清單1.2是按照符合慣例的編碼風(fēng)格對(duì)程序清單1.1中的代碼進(jìn)行修改后的版本。

程序清單1.2 一個(gè)簡(jiǎn)單的鏈表實(shí)現(xiàn)(整理后)

#include <stdio.h>
#include <stdlib.h>
 
struct linked_list {
    const char         *title;
    struct linked_list *next;
}
 
/* Creates and initializes a new linked list. */
static struct linked_list *init_linked_list(void);
 
/* Dumps the contents of a linked list */
static void dump_linked_list(struct linked_list *list);
 
/* Destroys a linked list */
static void destroy_linked_list(struct linked_list *list);
 
static const char *titles[] =
{
    "第1章 提高代碼可讀性",
    "第2章 用好寫好頭文件",
    "第3章 消除編譯警告",
    "第4章 常量的定義和使用",
    "第5章 充分利用構(gòu)建系統(tǒng)生成器"
};
 
int main(void)
{
    /* Creates and initialize a new linked list with chapter titles */
    struct linked_list *list = init_linked_list();
 
    printf("A new linked list has been created and initialized: \n");
    dump_linked_list(list);     // dump the contents
 
    destory_linked_list(list);  // destroy the list
    return 0;
}
 
struct linked_list *init_linked_list(void)
{
    struct linked_list *head = NULL;
 
    /* allocates a node for the head of the linked list */
    struct linked_list *head = (struct linked_list*)malloc(sizeof(*head));
 
    /* initializes the head node */
    head->title = titles[0];
    head->next = NULL;
 
    struct linked_list *p = head;
    for (int i = 1; i < 5; i++) {
        struct linked_list *a;
        a = (struct linked_list*)malloc(sizeof(*a));
        a->title = titles[i];
        a->next = NULL;
 
        p->next = a;
        p = a;
    }
 
    return head;
}

可以看到,修改之后的代碼排版錯(cuò)落有致,邏輯清晰,給人一種賞心悅目的感覺。除了排版,我們還在如下6個(gè)方面對(duì)原有的代碼做了調(diào)整,以便提高代碼可讀性以及代碼質(zhì)量。

struct linked_list結(jié)構(gòu)體中的第一個(gè)成員(elem)更名為更具實(shí)際意義的title

init_linked_list()函數(shù)聲明為static類型,避免命名污染。

display()函數(shù)重命名為dump_linked_list(),并聲明為static類型。display這個(gè)術(shù)語通常用于在窗口或者頁面中顯示一個(gè)圖形,而在本例中,展示一個(gè)鏈表通常意味著將其內(nèi)容轉(zhuǎn)儲(chǔ)(dump)到指定的文件或者標(biāo)準(zhǔn)輸出(標(biāo)準(zhǔn)輸出本質(zhì)上也是文件),以便事后查看或者調(diào)試。因此,使用dump這個(gè)術(shù)語來命名這個(gè)函數(shù),顯然要比使用display強(qiáng)很多。

新增destroy_linked_list()函數(shù),用于銷毀新創(chuàng)建的鏈表,并聲明為static類型。原有代碼在main()函數(shù)返回時(shí)并未做內(nèi)存的清理工作。盡管在這個(gè)簡(jiǎn)單的鏈表實(shí)現(xiàn)中不必如此嚴(yán)謹(jǐn),但作為專業(yè)程序員,我們應(yīng)該養(yǎng)成良好的習(xí)慣并逐漸形成條件反射:既然有鏈表的創(chuàng)建函數(shù),就應(yīng)該有對(duì)應(yīng)的鏈表銷毀函數(shù)。

init_linked_list()函數(shù)的實(shí)現(xiàn)中,移除了不必要且易混淆的temp變量。

使用sizeof(*head)的寫法替代了sizeof(struct linked_list)的寫法,避免代碼行過長(zhǎng)。

注意,上述代碼中未包含dump_linked_list()destroy_linked_list()兩個(gè)函數(shù)的實(shí)現(xiàn),有興趣的讀者可自行實(shí)現(xiàn)。

主站蜘蛛池模板: 社旗县| 元谋县| 宜君县| 达日县| 临海市| 澄城县| 荃湾区| 连南| 绥江县| 临颍县| 繁昌县| 桐庐县| 福州市| 稷山县| 灵武市| 吉隆县| 山东省| 安泽县| 巴塘县| 江山市| 喀喇沁旗| 安陆市| 滨海县| 乃东县| 玉林市| 长兴县| 西盟| 泰顺县| 天等县| 土默特左旗| 教育| 虎林市| 巴南区| 新绛县| 嘉善县| 芦山县| 临朐县| 平果县| 青川县| 囊谦县| 阿合奇县|