8

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?

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
Igor S.
  • 3,332
  • 1
  • 25
  • 33
  • 3
    I suggest you look into decorator design pattern. Of course you should think when to apply it. – Ivaylo Strandjev Jun 07 '13 at 08:53
  • 1
    Called _fluent interface_ (but not exclusively). I would suggest a line break before every `.`. – Joop Eggen Jun 07 '13 at 08:58
  • In my defense I didn't find this question: "Benefits..", also the question is askes so enigmaticly, I don't think many people will understand what is going on. – Igor S. Jun 07 '13 at 09:15

1 Answers1

2

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.

sateesh
  • 27,947
  • 7
  • 36
  • 45
  • 4
    If the class is called `Builder` or something similar instead, it is fairly clear IMO. – assylias Jun 07 '13 at 08:59
  • True but this question seems to be more general than that – Richard Tingle Jun 07 '13 at 09:14
  • 1
    It is not a bad practice, in fact it is used for many configuration objects, builder objects, and, hell, should be used anywhere where setters can be invoked more than 1-2 times. Should be pretty obvious that it returns itself and not a new instance, otherwise, javadoc should clearly state so. Examples that use that pattern: Hibernate Criteria, Astyanax, Cloudera's hadoop config, and many more. Surely their developers know a thing or two about developing apis, so in my opinion the accepted answer is totally wrong. – Nikola Yovchev Jun 07 '13 at 10:59