《C++ API設計》是一本不錯的講解C++接口設計以及軟件工程的書籍,作者是前皮克斯架構師。值得一讀。本文是在咬文嚼字,并非質疑作者觀點。
書名 | API C++Design for C++ |
---|---|
中譯本 | 《C++ API設計》 |
出版社 | 人民郵電出版社 |
版次 | 2013年9月第1版 |
2.4.3節 一致性
本節觀點沒有問題,就是闡述設計API時,要接口保持一致性,比如同一詞語的縮寫、相關函數中參數列表的順序等等。
第37頁(中譯版)有一小段文字列舉了一些違背API設計一致性的案例:
另一個例子是,標準C函數read( )和write( )將文件描述符作為其第一個參數,而fgets( )和fputs( )函數把文件描述符作為最后一個參數(Henning,2009)。
錯誤一目了然:
- 首先read( )和write( )并非標準C函數,而是屬于Unix/Linux系統調用(system call)。出自POSIX標準,而非ANSI C;
- 其次fgets( )和fputs( )函數的最后一個參數不是文件描述符,而是文件指針。
注意:fgets( )和fputs( )函數屬于ANSI C的標準庫函數,標準庫中的IO函數都是操縱的文件流指針(** FILE * **)而非文件描述符(file descriptor,實為整型)
原文給出了參考文獻(Henning,2009)
,通過查閱附錄,我找到這篇論文的信息:
M. Henning, API Design Matters, Commun. ACM 52 (5) (2009) 46-56
然后我就說ACM官網檢索并下載了這篇論文,發現該論文原文其實是沒有異議的,原文該段落寫的不錯,整體摘錄如下:
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.)
關鍵的部分是我加粗顯示的部分。閱讀上下文可知,該處大意是說 “Unix 標準IO庫在很多地方違反了一致性原則。比如,系統調用read()和write()將文件描述符放置在第一個參數,而標準庫的函數,比如fgets()和fputs()等都是將流指針(即FILE *)放置在最后一個參數(除fscanf()和fprintf()以外)”
系統調用IO和標準庫IO有著不一致性,同時標準庫IO自身也存在著不一致性:fscanf()和fprintf()放置文件流指針在第一個參數位置,而其他標準庫IO的函數則是放置在最后一個位置上。
筆者:其實fscanf()和fprintf()這么設計,是為了保持和scanf()/printf()、sscanf()/sprintf()的一致性嘛。但是為什么不把整個標準C庫的文件流指針設計成第一個參數呢。。。
后記
多了解一些違反一致的例子,可以方便記憶整個庫的API。