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

Not that I started learning Java yesterday, but I suddenly thought: why should we ever use void methods if we can return this instead? Thus, we can hook method calls to an object and make the code more readable (I know that this approach is gaining popularity already, but mainly with immutable objects, and allows you to forget about Java Beans convention). The only time I think of void that static methods are required.

+4
source share
1 answer

Presumably you will agree that some methods should tell you something - some kind of return value. It seems artificial and stupid that we "return the value we want to return if we really do not want to return anything, in which case we return this instead if it is not a static method, in which case we return void ."

What about:

  • if itโ€™s appropriate to return something, then return it
  • If this is not so, then not
  • (with some flaws for cases where the โ€œfreeโ€ API really makes sense)

Also: think about inheritance; if I have a virtual method Foo() , then the return type must be Foo to declare the type:

 public virtual SomeType Foo() {...} 

Now imagine a subclass of 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 account for poor APIs.

As a final thought: think of all the โ€œbuttocksโ€ when you really don't want to hook methods ...

+14
source

Source: https://habr.com/ru/post/1480679/


All Articles