Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

c#

oop

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.

like image 928
eugen-fried Avatar asked Dec 09 '22 15:12

eugen-fried


1 Answers

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:

  • 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)

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...

like image 163
Marc Gravell Avatar answered Dec 11 '22 09:12

Marc Gravell