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? 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). The only case I think of void
being required is static methods.
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
".
How about:
Also: think inheritance; if I have a virtual method Foo()
, then the return type would have to be Foo
's declaring type:
public virtual SomeType Foo() {...}
Now imagine I subclass SomeType
, with Bar : SomeType
and have an instance of Bar
:
Bar obj = new Bar();
obj.Foo().SomeOtherMethodOnBar(); // ERROR hey, where did my Bar go!?!?!
polymorphism does not respect fluent APIs.
As a final thought: think of all the "pop"s when you don't actually want to chain methods...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With