为什么 API 应该返回“void"? [英] Why should an API return 'void'?

查看:28
本文介绍了为什么 API 应该返回“void"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写 API 或可重用对象时,是否有任何技术原因为什么所有返回void"的方法调用不应该只返回this"(在 C++ 中为 *this)?

When writing an API or reusable object, is there any technical reason why all method calls that return 'void' shouldn't just return 'this' (*this in C++)?

比如使用string类,我们可以做这样的事情:

For example, using the string class, we can do this kind of thing:

string input= ...;
string.Join(input.TrimStart().TrimEnd().Split("|"), "-");

但我们不能这样做:

string.Join(input.TrimStart().TrimEnd().Split("|").Reverse(), "-");

..因为 Array.Reverse() 返回 void.

..because Array.Reverse() returns void.

还有许多其他示例,其中 API 具有大量返回空值的操作,因此代码最终看起来像:

There are many other examples where an API has lots of void-returning operations, so code ends up looking like:

api.Method1();
api.Method2();
api.Method3();

..但是完全可以这样写:

..but it would be perfectly possible to write:

api.Method1().Method2().Method3()

..如果 API 设计者允许这样做.

..if the API designer had allowed this.

遵循这条路线是否有技术原因?或者它只是一种风格,表示可变性/新对象?

Is there a technical reason for following this route? Or is it just a style thing, to indicate mutability/new object?

(x-ref 关于返回 void 的文体问题)

尾声

我接受了 Luvieere 的回答,因为我认为这最能代表意图/设计,但似乎有一些流行的 API 示例与此不同:

I've accepted Luvieere's answer as I think this best represents the intention/design, but it seems there are popular API examples out there that deviate from this :

在 C++ 中 cout <<setprecision(..) <<数< 似乎为了修改插入的下一个数据而改变 cout 对象.

In C++ cout << setprecision(..) << number << setwidth(..) << othernumber; seems to alter the cout object in order to modify the next datum inserted.

在 .NET 中,Stack.Pop()Queue.Dequeue() 都返回一个项目,但也会更改集合.

In .NET, Stack.Pop() and Queue.Dequeue() both return an item but change the collection too.

支持 ChrisW 和其他人详细了解实际性能成本.

Props to ChrisW and others for getting detailed on the actual performance costs.

推荐答案

更清楚地返回无效状态的方法有副作用.返回修改结果的那些应该没有副作用,包括修改原始输入.让方法返回 void 意味着它改变了它的输入或 API 的其他一些内部状态.

Methods that return void state more clearly that they have side effects. The ones that return the modified result are supposed to have no side effects, including modifying the original input. Making a method return void implies that it changes its input or some other internal state of the API.

这篇关于为什么 API 应该返回“void"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆