3

I am trying to use dialogs in Android. In the process, I encountered lines of code like the following:

alertDialogBuilder
            .setMessage("Click yes to exit!")
            .setCancelable(false)
            .setPositiveButton("Yes",new...

This notation is a bit strange for me as an old C++ programmer. Is this the same as,

alertDialogBuilder.setMessage("Click yes to exit!");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Yes",new...

If so, is this notation part of Java or unique to Android programming? What is the name of this notation (or method)?

Joel
  • 4,732
  • 9
  • 39
  • 54
adba
  • 477
  • 9
  • 25
  • 2
    http://en.wikipedia.org/wiki/Fluent_interface – SLaks Feb 04 '14 at 22:26
  • 1
    The benefits and drawbacks of this are discussed here; [Benefits and drawbacks of method chaining and a possibility to replace all void return parameters by the object itself](http://stackoverflow.com/questions/16976150/benefits-and-drawbacks-of-method-chaining-and-a-possibility-to-replace-all-void) – Richard Tingle Feb 04 '14 at 23:32

3 Answers3

3

This idiom is called method chaining and it's not specific to Java or Android. The trick is making methods that otherwise would return void return a reference to this, permitting long chains of method calls to the same object.

This idiom is quite useful when used in the builder pattern, like in your example. It's also a building block when designing fluent interfaces.

Joni
  • 108,737
  • 14
  • 143
  • 193
1

You can do same with C++ as well just return same object (this pointer). So ultimately you are calling next function on returned this pointer.

It is used in Builder Design Pattern!

Prakash
  • 4,479
  • 30
  • 42
1

In fact the code is:

alertDialogBuilder.setMessage("Click yes to exit!").setCancelable(false).setPositiveButton("Yes",new...

Maybe the formatting made you wonder. As you can see, and as mentioned by the other answers, the setMessage() apparently returns the alertDialogBuilder making it possible to call another method on it.

Peterdk
  • 15,625
  • 20
  • 101
  • 140