Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practice to return itself instead void in Java [duplicate]

My team mates introduce me to new practice writing method which will not return void.

public class Test {
   public Test doCalculations() {
      //code
      return this;
   }
   public Test appendTitle(String test) {
      //code
      return this;
   }
}

Instead of returning void they suggest to return object itself. One of the advantage of this aproach they say, you can chain methods.

Instead of writing:

 while(1) {
    test.appendTitle("aaa");
    test.doCalculations();
    map.add(test);
 }

You can write more elegant code:

 while(1) {
     map.add(test.appendTitle("aaa").doCalculations());
 }

What could be disadvantages of this aproach? Do you suggest to include it in daily use?

like image 932
Igor S. Avatar asked Jun 07 '13 08:06

Igor S.


People also ask

Is return on void good practice?

1) A Void Function Can Return: We can simply write a return statement in a void fun(). In fact, it is considered a good practice (for readability of code) to write a return; statement to indicate the end of the function.

Can we return 2 objects in Java?

Yes, we can return multiple objects from a method in Java as the method always encapsulates the objects and then returns.

Can a class return itself?

Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.

How do I stop Java from repeating code?

To avoid the problem of duplicated bugs, never reuse code by copying and pasting existing code fragments. Instead, put it in a method if it is not already in one, so that you can call it the second time that you need it.


1 Answers

I would say it is not a good practice. By looking at the method signature that returns an object, how can I know if it is a entirely new instance that is being returned or the existing one being returned.Note that in cases of immutable classes modified methods do return a new instance of the class.

like image 87
sateesh Avatar answered Oct 24 '22 19:10

sateesh