C++ FAQs, 2nd Edition, FAQ 5. 20
认为观点很好,受益匪浅,故此转贴上来与同仁共享
The original text:
Q: What's the best way to create a good interface to an abstraction?
A: Design the interface from the user's point of view (i.e., design the interface from the outside in). In other words, start by writing some sample user code.
Interface design decisions should be based primarily on the users' external perspective. In contrast, when the implementation is built before the interface is designed, the interface inevitably smells like the implementation. If the interface has to be explained to its users in terms of the implementation, then the implementation becomes cast in concrete.
=====================================================
译文
Q:为一个抽象(类)创造良好接口的最好办法是什么?
A:从用户的观点来设计接口 (比如,从外缘开始,逐渐趋向中心)。也就是,从试着写一些用户代码开始。
接口设计应该主要是基于用户的外部观点。相反的,如果在接口设计好之前就已经做好了实现,那么接口不可避免地会想类的实现一样烂。如果必须向用户解释接口的实现细节,那么这个实现就变得固化了(也即,不容易改变)。
个人体会:试着从用户的角度思考类的接口设计:如果我要用这个类,我会希望它提供哪些功能和属性?有没有必要了解功能实现的细节,还是只要根据类设计的规范直接调用它就OK了?这样就能让一个封装暴露出来的接口尽可能的少而实用,大大减少无用代码的数量。