开发者

Why Java can take multiple parameters but can return only a single object?

Why was java defined such that methods may take as input multiple parameters,

but may only return a single object (or void)?

开发者_StackOverflow社区

Did it make the language somehow easier to implement or use?


Probably because this is the way that C and C++ do it, and the Java language syntax is very similar to (and probably based on) those languages.

In fact, according to this article, Gosling started by extending the C++ compiler, so it makes sense that he would follow much of the same syntax:

To make development a more platform-neutral process (and thus accommodate the consumer market's demand for CPU flexibility), Gosling began by extending the C++ compiler.


Maybe the intention was that multiple return values be encapsulated in an object?


I don't know for sure, but I imagine that Java is executed like any other stack-based runtime. Which means that passing items as parameters into a method is done easily by simply pushing them onto the stack before transferring control to the method. Return values are probably handled in the VM like C and C++ do - the return value is always placed in a register, which is by nature single-valued.

It's not a big problem, though, because with generics, returning multiple values can be handled in a type-safe way by returning an instance of something like Tuple<type1, type2, type3>, which isn't too great a burden to bear in most cases.


My guess would be convention: that's what the major OO languages do/did, so that's what Java did. However, the official argument would probably be the same as the one about closures - don't include things that will cloud up the standard syntax for mundane tasks with not-really-needed tasks. Or maybe they figured that a single method should be returning a set of related values that should/could go into an object. Or maybe they just didn't think of it/have the time (pretty standard developer fare).

On a related note, I found this discussion of using closures to mock multiple returns: http://weblogs.java.net/blog/brucechapman/archive/2007/11/closures_and_mu.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜