1

When I write a class with several voids:

public class MyObj {
    public void doSomething() { /* does something */ }
    public void doSomethingElse() { /* does something else */ }
    ...
}

I can use the following code:

MyObj myObj = new MyObj();
myObj.doSomething(); // does something
myObj.doSomethingElse(); // does something else

But if I write the class like this:

public class MyObj {
    public MyObj doSomething() {
        // do something;
        return this;
    }
    public MyObj doSomethingElse() {
        // do something else;
        return this;
    }
}

I can use the following code to accomplish the same task:

MyObj myObj = new MyObj();
MyObj.doSomething().doSomethingElse(); // does something and does something else.

I've seen the 2nd form in JavaScript (jQuery):

$("#myDialog").dialog().focus().mySuperLongNameHomeMadeBullshitFunction().remove();

So my question is, in Java, what are the pros and cons of using the concatenating form or the standard? (I'm really not going to change to the second, just curious, as we all are).

Twinone
  • 2,949
  • 4
  • 28
  • 39

2 Answers2

4

Method chaining allows you to call the methods in a single expression.

This can be useful in situations where you cannot use multiple statements -- e.g., this() and super().

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
0

Using method chaining can allow to create some DSL using fluent API and create clearer code.

It can allow to be more concise and more meaningful while doing the exact same thing.

benzonico
  • 10,635
  • 5
  • 42
  • 50