简体   繁体   English

为什么我们需要OOP语言中的方法的void返回类型?

[英]Why would we need void return type from methods in OOP languages?

It's not that I've started learning Java yesterday, but suddenly I thought, why would we ever use void methods, if we can return this instead? 这并不是说我昨天开始学习Java,但我突然想到,为什么我们会使用void方法,如果我们可以返回this呢? That way we can chain method calls on object and make the code more readable (I know that this approach is gaining popularity already, but mostly with immutable objects, and lets forget about Java Beans convention). 这样我们可以在对象上链接方法调用并使代码更具可读性(我知道这种方法已经越来越受欢迎,但主要是使用不可变对象,让我们忘记Java Beans约定)。 The only case I think of void being required is static methods. 我认为void的唯一情况是静态方法。

Presumably you will accept that some methods need to tell you something - some kind of return value. 大概你会接受一些方法需要告诉你一些东西 - 某种返回值。 It seems artificial and obtuse that we would "return the value we want to return, unless we don't actually want to return anything, in which case we return this instead, unless it is a static method, in which case we return void ". 我们会“返回我们想要返回的值,这似乎是人为的和迟钝的,除非我们实际上不想返回任何东西,在这种情况下我们将返回this ,除非它是一个静态方法,在这种情况下我们返回void ” 。

How about: 怎么样:

  • if it is appropriate to return something, then return it 如果适合返回某些东西,则返回它
  • if if isn't, then don't 如果不是,那就不要了
  • (with some wriggle room for cases where a "fluent" API genuinely makes sense) (对于“流利”API真正有意义的情况,有一些蠕动空间)

Also: think inheritance; 另外:认为继承; if I have a virtual method Foo() , then the return type would have to be Foo 's declaring type: 如果我有一个虚方法Foo() ,那么返回类型必须是Foo的声明类型:

public virtual SomeType Foo() {...}

Now imagine I subclass SomeType , with Bar : SomeType and have an instance of Bar : 现在假设我使用Bar : SomeType子类SomeType ,并且有一个Bar实例:

Bar obj = new Bar();
obj.Foo().SomeOtherMethodOnBar(); // ERROR hey, where did my Bar go!?!?!

polymorphism does not respect fluent APIs. 多态性不尊重流畅的API。

As a final thought: think of all the "pop"s when you don't actually want to chain methods... 作为最后的想法:当你实际上不想链接方法时,想想所有的“流行音乐”......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM