《C++ API設(shè)計(jì)》是一本不錯(cuò)的講解C++接口設(shè)計(jì)以及軟件工程的書籍,作者是前皮克斯架構(gòu)師。值得一讀城舞。本文是在咬文嚼字,并非質(zhì)疑作者觀點(diǎn)寞酿。
書名 | API C++Design for C++ |
---|---|
中譯本 | 《C++ API設(shè)計(jì)》 |
出版社 | 人民郵電出版社 |
版次 | 2013年9月第1版 |
2.4.3節(jié) 一致性
本節(jié)觀點(diǎn)沒有問題家夺,就是闡述設(shè)計(jì)API時(shí),要接口保持一致性伐弹,比如同一詞語的縮寫拉馋、相關(guān)函數(shù)中參數(shù)列表的順序等等。
第37頁(中譯版)有一小段文字列舉了一些違背API設(shè)計(jì)一致性的案例:
另一個(gè)例子是,標(biāo)準(zhǔn)C函數(shù)read( )和write( )將文件描述符作為其第一個(gè)參數(shù)煌茴,而fgets( )和fputs( )函數(shù)把文件描述符作為最后一個(gè)參數(shù)(Henning随闺,2009)。
錯(cuò)誤一目了然:
- 首先read( )和write( )并非標(biāo)準(zhǔn)C函數(shù)蔓腐,而是屬于Unix/Linux系統(tǒng)調(diào)用(system call)矩乐。出自POSIX標(biāo)準(zhǔn),而非ANSI C回论;
- 其次fgets( )和fputs( )函數(shù)的最后一個(gè)參數(shù)不是文件描述符绰精,而是文件指針。
注意:fgets( )和fputs( )函數(shù)屬于ANSI C的標(biāo)準(zhǔn)庫(kù)函數(shù)透葛,標(biāo)準(zhǔn)庫(kù)中的IO函數(shù)都是操縱的文件流指針(** FILE * **)而非文件描述符(file descriptor笨使,實(shí)為整型)
原文給出了參考文獻(xiàn)(Henning,2009)
僚害,通過查閱附錄硫椰,我找到這篇論文的信息:
M. Henning, API Design Matters, Commun. ACM 52 (5) (2009) 46-56
然后我就說ACM官網(wǎng)檢索并下載了這篇論文,發(fā)現(xiàn)該論文原文其實(shí)是沒有異議的萨蚕,原文該段落寫的不錯(cuò)靶草,整體摘錄如下:
Consistency is important because not only does it make things easier to use and memorize, but it also enables transference of learning: having learned a part of an API, the caller also has learned much of the remainder of the API and so experiences minimal friction. Transference is important not only within APIs but also across APIs—the more concepts APIs can adopt from each other,the easier it becomes to master all of them. (The Unix standard I/O library violates this idea in a number of places. For example, the read() and write() system calls place the file descriptor first, but the standard library I/O calls, such as fgets() and fputs(), place the stream pointer last, except for fscanf() and fprintf(), which place it first.This lack of parallelism is jarring to many people.)
關(guān)鍵的部分是我加粗顯示的部分蓖柔。閱讀上下文可知卦碾,該處大意是說 “Unix 標(biāo)準(zhǔn)IO庫(kù)在很多地方違反了一致性原則鳍咱。比如逻族,系統(tǒng)調(diào)用read()和write()將文件描述符放置在第一個(gè)參數(shù),而標(biāo)準(zhǔn)庫(kù)的函數(shù)础钠,比如fgets()和fputs()等都是將流指針(即FILE *)放置在最后一個(gè)參數(shù)(除fscanf()和fprintf()以外)”
系統(tǒng)調(diào)用IO和標(biāo)準(zhǔn)庫(kù)IO有著不一致性排监,同時(shí)標(biāo)準(zhǔn)庫(kù)IO自身也存在著不一致性:fscanf()和fprintf()放置文件流指針在第一個(gè)參數(shù)位置仇奶,而其他標(biāo)準(zhǔn)庫(kù)IO的函數(shù)則是放置在最后一個(gè)位置上捻艳。
筆者:其實(shí)fscanf()和fprintf()這么設(shè)計(jì)驾窟,是為了保持和scanf()/printf()、sscanf()/sprintf()的一致性嘛认轨。但是為什么不把整個(gè)標(biāo)準(zhǔn)C庫(kù)的文件流指針設(shè)計(jì)成第一個(gè)參數(shù)呢绅络。。嘁字。
后記
多了解一些違反一致的例子恩急,可以方便記憶整個(gè)庫(kù)的API。