【发布时间】:2017-06-17 12:10:32
【问题描述】:
现有的 C API 如下所示:
//data
typedef struct {int properties;} Widget;
//interface
Widget* SetWidth(Widget *const w, int width){
// ...
return w;
}
Widget* SetHeight(Widget *const w, int height){
// ...
return w;
}
Widget* SetTitle(Widget *const w, char* title){
// ...
return w;
}
Widget* SetPosition(Widget *const w, int x, int y){
// ...
return w;
}
第一个参数始终是指向实例的指针,转换实例的函数始终将其作为指针返回。
我认为这样做是为了支持某种Method Chaining?
当函数作为方法存在于对象范围内时,方法链接在语言中才有意义。鉴于 API 处于当前状态,我将继续使用它:
int main(void) {
Widget w;
SetPosition(SetTitle(SetHeight(SetWidth(&w,400),600),"title"),0,0);
}
我可以在 C 中使用任何技术来获得与其他语言相同的流动性吗?
【问题讨论】:
-
并非如此。流体接口一般只存在于 OO 语言中。
-
它在 C 中用处不大,原因有二:一,没有例外。返回值通常用于指示成功或失败。二、手动内存管理和无RAII。
-
C 没有方法。它有功能。你的问题没有意义。
-
@Barmar C can be OOP。种。
-
@Barmar:流利,不流畅。除非你想通过管道泵送你的接口。
标签: c macros api-design fluent-interface method-chaining