Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to achieve method chaining in Java?

I want to achieve method chaining in Java.

How can I achieve it?

Also let me know when to use it.

public class Dialog {       public Dialog() {       }       public void setTitle(String title) {           //Logic to set title in dialog      }       public void setMessage(String message) {           //Logic to set message      }            public void setPositiveButton() {           //Logic to send button      } }    

I want to create method chaining that I can use as follows:

new Dialog().setTitle("Title1").setMessage("sample message").setPositiveButton(); 

or like

new Dialog().setTitle("Title1").setMessage("sample message"); 

or like

new Dialog().setTitle("Title1").setPositiveButton(); 
like image 910
Bug Avatar asked Jan 17 '14 07:01

Bug


People also ask

How do you create a chaining method in Java?

Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.).

What is constructor chaining and how is it achieved in Java?

Constructor chaining is the process of calling a sequence of constructors. We can do it in two ways: by using this() keyword for chaining constructors in the same class. by using super() keyword for chaining constructors from the parent class.

Which of the following methods are related to method chaining?

In Java, method chaining is the chain of methods being called one after another. It is the same as constructor chaining but the only difference is of method and constructor. In this section, we will discuss the method chaining in Java.


2 Answers

Have your methods return this like:

public Dialog setMessage(String message) {     //logic to set message     return this; } 

This way, after each call to one of the methods, you'll get the same object returned so that you can call another method on.

This technique is useful when you want to call a series of methods on an object: it reduces the amount of code required to achieve that and allows you to have a single returned value after the chain of methods.

An example of reducing the amount of code required to show a dialog would be:

// Your Dialog has a method show()  // You could show a dialog like this: new Dialog().setMessage("some message").setTitle("some title")).show(); 

An example of using the single returned value would be:

// In another class, you have a method showDialog(Dialog) // Thus you can do: showDialog(new Dialog().setMessage("some message").setTitle("some title")); 

An example of using the Builder pattern that Dennis mentioned in the comment on your question:

new DialogBuilder().setMessage("some message").setTitle("some title").build().show(); 

The builder pattern allows you to set all parameters for a new instance of a class before the object is being built (consider classes that have final fields or objects for which setting a value after it's been built is more costly than setting it when it's constructed).

In the example above: setMessage(String), setTitle(String) belong to the DialogBuilder class and return the same instance of DialogBuilder that they're called upon; the build() method belongs to the DialogBuilder class, but returns a Dialog object the show() method belongs to the Dialog class.

Extra

This might not be related to your question, but it might help you and others that come across this question.

This works well for most use cases: all use cases that don't involve inheritance and some particular cases involving inheritance when the derived class doesn't add new methods that you want to chain together and you're not interested in using (without casting) the result of the chain of methods as an object of the derived.

If you want to have method chaining for objects of derived classes that don't have a method in their base class or you want the chain of methods to return the object as a reference of the derived class, you can have a look at the answers for this question.

like image 184
lucian.pantelimon Avatar answered Oct 18 '22 22:10

lucian.pantelimon


Just add a static builder method, and create another set of the setter methods. For example

class Model {    private Object FieldA;     private Object FieldB;     public static Model create() {        return new Model();    }     public Model withFieldA(Object value) {        setFieldA(value);        return this;    }     public Model withFieldB(Object value) {        setFieldB(value);        return this;    } } 

...

And use it like

 Model m = Model.create().withFieldA("AAAA").withFieldB(1234); 
like image 22
Vagif Avatar answered Oct 18 '22 22:10

Vagif