为什么要一个API返回“无效”? [英] Why should an API return 'void'?

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

问题描述

在写一个API或可重复使用的对象,有什么技术原因,所有的方法调用返回无效,不应仅仅返回'这个'(* ++在C)?

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("|"), "-");

但我们不能做到这一点:

but we can't do this:

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

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

..because Array.Reverse() returns void.

有凡API有许多空隙恢复操作的许多其他例子,所以code结束看起来像:

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 <一个href=\"http://stackoverflow.com/questions/1240876/stylistic-question-concerning-returning-void\">http://stackoverflow.com/questions/1240876/stylistic-question-concerning-returning-void)

后记

我已经接受Luvieere的回答,因为我觉得这个最重presents意图/设计,但似乎也有流行的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&LT;&LT;集precision(..)LT;&LT;数字&LT;&LT; setwidth(..)LT;&LT; othernumber; 似乎改变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状态。返回的修改后的结果的那些应该有任何副作用,包括修改原始输入。制作的方法返回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返回“无效”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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