DEV Community

loading...

Method Chaining In Java

skptricks profile image skptricks ・1 min read

Post Link : https://www.skptricks.com/2018/08/method-chaining-in-java.html

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.

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.

Discussion (1)

pic
Editor guide
Collapse
firuzzz profile image
Jose Luis Romero

So... U just copy/paste articles? A very bad one btw, with a horrible example of pipeline pattern which doesn't show its strength or expose its weakness
Java has hundreds of well design patterns like StringBuilder, all Stream implementation