API设计准则(转)

Wesley13
• 阅读 450

Six Characteristics of Good APIs

优良API的六个特征

An API is to the programmer what a GUI is to the end-user. The ‘P’ in API stands for “Programmer”, not “Program”, to highlight the fact that APIs are used by programmers, who are humans.
API于一个程序员正如GUI于使用者. API中的P表示程序员, 而不是程序, 以凸显出API是供程序员使用的, 而程序员也是人类.

In his Qt Quarterly 13 article about API design [doc.qt.nokia.com], Matthias tells us he believes that APIs should be minimal and complete, have clear and simple semantics, be intuitive, be easy to memorize, and lead to readable code.
在他的Qt Quarterly 13 article about API design[doc.qt.nokia.com]中, Matthias告诉我们他认为API应该小而全, 有清晰和简单的语义, 直观易记, 从而使代码易读.

  • Be minimal: A minimal API is one that has as few public members per class and as few classes as possible. This makes it easier to understand, remember, debug, and change the API.
  • : 一个小的API应该经可能的有较少的类和较少的类公共成员. 这让它易于理解, 记忆, 调试和更改
  • Be complete: A complete API means the expected functionality should be there. This can conflict with keeping it minimal. Also, if a member function is in the wrong class, many potential users of the function won’t find it.
  • : 一个全的API, 意味着预期的功能都具有. 这也许会和小冲突. 但是, 如果一个成员函数存在与一个错误的类里面, 许多该函数的潜在用户很难发现他们.
  • Have clear and simple semantics: As with other design work, you should apply the principle of least surprise. Make common tasks easy. Rare tasks should be possible but not the focus. Solve the specific problem; don’t make the solution overly general when this is not needed. (For example, QMimeSourceFactory in Qt 3 could have been called QImageLoader and have a different API.)
  • 清晰和简单的语义: 就像和其他的设计工作一样, 你应该运用最小惊奇定理. 让普通的任务容易完成. 稀有的任务也能完成但不是关注点. 解决特定的问题, 没必要的话不要让解决方法过于普适. (例如, Qt 3中的QMimeSourceFactory应该被定义为QImageLoader, 并且有不同的API)
  • Be intuitive: As with anything else on a computer, an API should be intuitive. Different experience and background leads to different perceptions on what is intuitive and what isn’t. An API is intuitive if a semi-experienced user gets away without reading the documentation, and if a programmer who doesn’t know the API can understand code written using it.
  • 直观: 与计算机里的其他东西一样, API应该是直观的. 不同的经验和背景导致对直观的不同理解. 如果一个稍有经验的人不需要查阅文档就能理解API, 或者是一个不了解API的程序员能明白用这个API写的代码, 那么这个API就是直观的.
  • Be easy to memorize: To make the API easy to remember, choose a consistent and precise naming convention. Use recognizable patterns and concepts, and avoid abbreviations.
  • 易记: 为了让API易记, 选择一个统一且精确的命名规范. 使用易记的模式和概念, 避免缩写
  • Lead to readable code: Code is written once, but read (and debugged and changed) many times. Readable code may sometimes take longer to write, but saves time throughout the product’s life cycle.
  • 使代码易读: 代码只用写一次, 但是会被阅读(或者调试, 修改)很多次. 易读的代码需要较长的时间去书写, 但是在产品的生命周期里节省了可观的时间

Finally, keep in mind that different kinds of users will use different parts of the API. While simply using an instance of a Qt class should be intuitive, it’s reasonable to expect the user to read the documentation before attempting to subclass it.
最后, 牢记在心, 不同的用户会使用API的不同部分. 虽然简单的使用一个Qt类的实例是很直观的, 但是用户应该在继承类之前阅读文档.

Static Polymorphism

静态多态性

Similar classes should have a similar API. This can be done using inheritance where it makes sense — that is, when run-time polymorphism is used. But polymorphism also happens at design time. For example, if you exchange a QProgressBar with a QSlider, or a QString with a QByteArray, you’ll find that the similarity of APIs makes this replacement very easy. This is what we call “static polymorphism”.
相似的类应该具有相似的API. 这可以通过在需要的地方使用继承来做到 — 那就是说, 当用到运行时多态的时候. 但是多态也会出现在设计的时候. 例如, 如果一个QProgressBar去替换QSlider, 或者一个QString去替换QByteArray, 你会发现相似的API会让替换很容易. 这就是我们说的静态多态性.

Static polymorphism also makes it easier to memorize APIs and programming patterns. As a consequence, a similar API for a set of related classes is sometimes better than perfect individual APIs for each class.
静态多态性也让API和编程模式易记. 这样的结果就是, 一个相似的API对应着一些相关类的集合, 有些时候比每个类的完美的独立的API好得多.

In general, in Qt, we prefer to rely on static polymorphism than on actual inheritance when there’s no compelling reason to do otherwise. This keeps the number of public classes in Qt down and makes it easier for new Qt users to find their way around in the documentation.
通常来说, 在Qt里, 继承上我们选择依赖静态多态性, 当没有无法控制的原因让我们另外换一种做法的时候. 这让Qt里类的数量减少了, 并且让新的Qt用户更容易在文档里找到他们.

Good: QDialogButtonBox and QMessageBox have similar APIs for dealing with buttons (addButton(), setStandardButtons(), etc.), without publicly inheriting from some “QAbstractButtonBox” class.
: QDialogButtonBox和QMessageBox在处理按钮时有相似的API(addButton(), setStandardButtons(), 等等), 并没有从类似于“QAbstractButtonBox”这样的类继承而来.

Bad: QAbstractSocket is inherited both by QTcpSocket and QUdpSocket, two classes with very different modes of interaction. Nobody seems to have ever used (or been able to use) a QAbstractSocket pointer in a generic and useful way.
: QAbstractSocket继承于QTcpSocket和QUdpSocket, 这两个类有着非常不同的交互. 貌似没人能通用且有效的使用QAbstractSocket指针.

Dubious: QBoxLayout is the base class of QHBoxLayout and QVBoxLayout. Advantage: Can use a QBoxLayout and call setOrientation() in a toolbar to make it horizontal/vertical. Disadvantages: One extra class, and possibility for users to write ((QBoxLayout *)hbox)->setOrientation(Qt::Vertical), which makes little sense.
不好不坏的: QBoxLayout是QHBoxLayout和QVBoxLayout的基类. 好处: 可以使用 QBoxLayout 并且在toolbar中调用tsetOrientation()来让它横向/竖向. 坏处: 多了一个类, 可能用户会写出((QBoxLayout *)hbox)->setOrientation(Qt::Vertical)这样的代码, 虽然有一些意义.

Property-Based APIs

基于属性的API

Newer Qt classes tend to have a “property-based API”. E.g.:
新的Qt类倾向于”基于属性的API”, 例如:

1
2
3
4

QTimer timer; timer.setInterval(1000); timer.setSingleShot(true); timer.start();

By property, we mean any conceptual attribute that’s part of the object’s state — whether or not it’s an actual Q_PROPERTY. When practicable, users should be allowed to set the properties in any order; i.e., the properties should be orthogonal. For example, the preceding code could be written.
提到属性, 我们是指任何属于对象状态的概念性属性 – 不管其是不是Q_PROPERTY. 当可行的时候, 用户应该能以任何顺序设置属性. 那就是说, 属性是正交的. 例如, 前面的代码也可以这样:

1
2
3
4

QTimer timer; timer.setSingleShot(true); timer.setInterval(1000); timer.start();

For convenience, we can also write timer.start(1000).
方便起见, 我们也可以写 timer.start(1000);

Similarly, for QRegExp, we have
类似的, 对于QRegExp, 我们有:

1
2
3
4

QRegExp regExp; regExp.setCaseSensitive(Qt::CaseInsensitive); regExp.setPattern("***.*"); regExp.setPatternSyntax(Qt::WildcardSyntax);

To implement this type of API, it pays off to construct the underlying object lazily. E.g. in QRegExp’s case, it would be premature to compile the “***.*” pattern in setPattern() without knowing what the pattern syntax will be.
为了实现这种类型的API, 延迟创建底层对象是值得的. 比如, 在QRegExp的例子里, 可以提前在Pattern里编译”***.*”模式, 而不需要知道模式语法是什么.

Properties often cascade; in that case, we must proceed carefully. Consider the “default icon size” provided by the current style vs. the “iconSize” property of QToolButton:
属性是可以层叠的. 在这种案例里, 我们必须小心处理. 设想当前样式提供的”默认图标大小”和QToolButton的”iconSize”属性:

1
2
3
4
5
6
7

toolButton->iconSize(); // returns the default for the current style toolButton->setStyle(otherStyle); toolButton->iconSize(); // returns the default for otherStyle toolButton->setIconSize(QSize(52, 52)); toolButton->iconSize(); // returns (52, 52) toolButton->setStyle(yetAnotherStyle); toolButton->iconSize(); // returns (52, 52)

Notice that once we set iconSize, it stays set; changing the current style doesn’t change a thing. This is good. Sometimes, it’s useful to be able to reset a property. Then there are two approaches:
注意一但我们设置了iconSize, 他就一直被设置了. 改变当前样式对它并没有影响. 这很好. 有时候, 重置一个属性是非常有用的. 有两种方法可以做到:

  • pass a special value (such as QSize(), -1, or Qt::Alignment(0)) to mean “reset”
  • 传递一个特殊的值(例如QSize(), -1, 或者Qt::Alignment(0))来表示重置
  • have an explicit resetFoo() or unsetFoo() function
  • 有一个显示的resetFoo()或者unsetFoo()的函数

For iconSize, it would be enough to make QSize() (i.e., QSize(-1, -1)) mean “reset”.
对于iconSize, 用QSize() (例如QSize(-1,-1)) 来重置就足够了.

In some cases, getters return something different than what was set. E.g. if you call widget->setEnabled(true), you might still get widget->isEnabled() return false, if the parent is disabled. This is OK, because that’s usually what we want to check (a widget whose parent is disabled should be grayed out too and behave as if it were disabled itself, at the same time as it remembers that deep inside, it really is “enabled” and waiting for its parent to become enabled again), but must be documented properly.
在有些案例中, getter的返回和设置的值不同. 比如, 如果你调用widget->setEnabled(true), 你仍然可能会从widget->isEnabled()那里得到false, 如果widget的父亲是被禁用了的. 这没什么, 因为我们通常想去检查(一个widget的父亲被禁止了, 它也应该变灰并且好像是它自己禁止的, 同时, 当其被激活的时候, 它会等待它的父亲被激活), 但是必须在文档里写清楚.

来源: http://lyxint.com/archives/256

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Wesley13 Wesley13
3年前
Java8 日期、时间操作
<divid"cnblogs\_post\_body"class"blogpostbody"<p一、简介</p<p  在Java8之前,日期时间API一直被开发者诟病,包括:java.util.Date是可变类型,SimpleDateFormat非线程安全等问题。故此,Java8引入了一套全新的日期时间处理API,新的API基于ISO标准
Stella981 Stella981
3年前
HIVE 时间操作函数
日期函数UNIX时间戳转日期函数: from\_unixtime语法:   from\_unixtime(bigint unixtime\, string format\)返回值: string说明: 转化UNIX时间戳(从19700101 00:00:00 UTC到指定时间的秒数)到当前时区的时间格式举例:hive   selec
Wesley13 Wesley13
3年前
03.Android崩溃Crash库之ExceptionHandler分析
目录总结00.异常处理几个常用api01.UncaughtExceptionHandler02.Java线程处理异常分析03.Android中线程处理异常分析04.为何使用setDefaultUncaughtExceptionHandler前沿上一篇整体介绍了crash崩溃
Wesley13 Wesley13
3年前
Java日期时间API系列35
  通过Java日期时间API系列1Jdk7及以前的日期时间类(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.cnblogs.com%2Fxkzhangsanx%2Fp%2F12032719.html)中得知,Java8以前除了java.sql.Timestamp扩充
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这