Monday, August 27, 2018

Method chaining in Java

The term method chaining refers to both a design and a convention. Each method returns an object, allowing the calls to be chained together in a single statement. Chaining is syntactic sugar which eliminates the need for intermediate variables. A method chain is also known as a train wreck due to the increase in the number of methods that come one after another in the same line that occurs as more methods are chained together even though line breaks are often added between methods.

It applies to classes and methods where:
  • multiple methods are potentially going to be called on the same object;
  • the methods in question need no return value.
The idea of method chaining is that if the methods need no "useful" return value, then the method can return this

Method Chaining :
class User {
 
private String name;
private int age;

// In addition to having the side-effect of setting the attributes in question,
// the setters return "this" (the current Person object) to allow for further chained method calls.

public User setName(String name) {
    this.name = name;
    return this;
}

public User setAge(int age) {
    this.age = age;
    return this;
}

public void getUserDetails() {
    System.out.println("User name is " + name + " and " + age + " years old.");
}

// Usage:
public static void main(String[] args) {
 User user= new User();   
    user.setName("skptricks").setAge(22).getUserDetails();
}
}

Ouput :
User name is skptricks and 22 years old.

Without Method Chaining :
class User {
 
private String name;
private int age;

//Per normal Java style, the setters return void.

public void setName(String name) {
    this.name = name;
    
}

public void setAge(int age) {
    this.age = age;
   
}

public void getUserDetails() {
    System.out.println("User name is " + name + " and " + age + " years old.");
}

// Usage:
public static void main(String[] args) {
 User user = new User();   
 user.setName("skptricks");
    user.setAge(22);
    user.getUserDetails();
}
}

Ouput :
User name is skptricks and 22 years old.

Hope you like this simple example for method chaining. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

1 comment: