Week 22 — What is method chaining?

Question of the Week #22
What is method chaining?
5 Replies
Eric McIntyre
Eric McIntyre2y ago
Method chaining is when you return the whole object again, so that you can call a method on the method. An exaple:
public class Test{
private bool valid;
private String name;

public Test setToValid(){
this.valid = true;
return this;
}

public Test changeName(String name){
this.name = name;
return this;
}
}

public static void main(String[] args){
Test test = new Test();
// Here it's now possible to call the two methods in one line, because you returned the object
test.setToValid().changeName("New name");
}
public class Test{
private bool valid;
private String name;

public Test setToValid(){
this.valid = true;
return this;
}

public Test changeName(String name){
this.name = name;
return this;
}
}

public static void main(String[] args){
Test test = new Test();
// Here it's now possible to call the two methods in one line, because you returned the object
test.setToValid().changeName("New name");
}
Submission from Giotsche#5027
Eric McIntyre
Eric McIntyre2y ago
Method chaining in Java is a programming technique where multiple methods are called on the same object in a single line of code, with each method returning the object itself, allowing the next method to be called on the same object. This is achieved by returning the object (this) at the end of each method call. For example, consider the following code:
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("world");
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" ").append("world");
Here, StringBuilder is a class in Java that represents a mutable sequence of characters. The append method is used to append the specified string to the sequence. In the above example, the append method is called three times in a single line, and each call returns the same StringBuilder object, allowing the next method to be called on the same object. Method chaining can make code more concise and readable by reducing the number of intermediate variables and lines of code. However, it can also make code harder to read and debug if used excessively or improperly. Therefore, it is important to use method chaining judiciously and only when it improves the readability and maintainability of the code.
Submission from Brayan1a1#9991
Eric McIntyre
Eric McIntyre2y ago
Method chaining in Java refers to the practice of calling multiple methods on an object in a single line, where each method returns the modified object. This technique allows for concise and readable code. Here's an example:
public class Person {
private String firstName;
private String lastName;
private int age;

public Person setFirstName(String firstName) {
this.firstName = firstName;
return this;
}

public Person setLastName(String lastName) {
this.lastName = lastName;
return this;
}

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

@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
'}';
}
}
public class Person {
private String firstName;
private String lastName;
private int age;

public Person setFirstName(String firstName) {
this.firstName = firstName;
return this;
}

public Person setLastName(String lastName) {
this.lastName = lastName;
return this;
}

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

@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", age=" + age +
'}';
}
}
Now, let's see an example of method chaining with the Person class:
public class Main {
public static void main(String[] args) {
Person person = new Person()
.setFirstName("John")
.setLastName("Doe")
.setAge(30);

System.out.println(person);
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person()
.setFirstName("John")
.setLastName("Doe")
.setAge(30);

System.out.println(person);
}
}
In the above example, we create a Person object and use method chaining to set its firstName, lastName, and age properties in a single line. Each method call returns the modified Person object, allowing us to chain the subsequent method calls. The output of the above code will be:
Person{firstName='John', lastName='Doe', age=30}
Person{firstName='John', lastName='Doe', age=30}
Method chaining can be particularly useful when setting multiple properties of an object or configuring complex objects with a fluent API.
⭐ Submission from Daulet#3448
Eric McIntyre
Eric McIntyre2y ago
One might want to run a method on the returned result of another method. For example, one could have the following classes
public class A{
public void sayHi(){
System.out.println("Hi");
}
}
public class B{
private A a=new A();
public A getA(){
return a;
}
}
public class A{
public void sayHi(){
System.out.println("Hi");
}
}
public class B{
private A a=new A();
public A getA(){
return a;
}
}
With an instance of B, it is possible to get the A field and call the method sayHi on that:
B b = new B();//some B instance
A a = b.getA();//get the result of getA()
a.sayHi();//call the method sayHi() on the result of getA()
B b = new B();//some B instance
A a = b.getA();//get the result of getA()
a.sayHi();//call the method sayHi() on the result of getA()
However, it is possible to "chain" together the calls of getA() and sayHi():
B b = new B();//some B instance
b.getA().sayHi();//call getA(), get its result and call sayHi() on it
B b = new B();//some B instance
b.getA().sayHi();//call getA(), get its result and call sayHi() on it
This is especially useful when there is more than one method being chained together. For example, it is possible to add two more classes C and D as follows:
public class C{
private B b=new B();
public B getB(){
return b;
}
}
public class D{
private C c=new C();
public C getC(){
return c;
}
}
public class C{
private B b=new B();
public B getB(){
return b;
}
}
public class D{
private C c=new C();
public C getC(){
return c;
}
}
Then, the following code would be required to call sayHi() starting from a D instance:
D d = new D();
C c = d.getC();
B b = c.getB();
A a = b.getA();
a.sayHi();
D d = new D();
C c = d.getC();
B b = c.getB();
A a = b.getA();
a.sayHi();
With method chaining, this requires less boilerplate:
D d = new D();
d.getC().getB().getA().sayHi();
D d = new D();
d.getC().getB().getA().sayHi();
Eric McIntyre
Eric McIntyre2y ago
A common application of method chaining is the Stream API which was introduced with Java 8. For example, the following code could be used for converting a List<String> to another List containing all Strings from the first list consisting of 5 characters that start with an A or a and turn all of these Strings to uppercase:
List<String> strings = new ArrayList<>();
//TODO fill list with some strings
List<String> stringsWithFiveLettersStartingWithA = strings
.stream()
.filter(s->s.length()==5)
.map(String::toUpperCase)
.filter(s->s.startsWith("A"))
.toList();
List<String> strings = new ArrayList<>();
//TODO fill list with some strings
List<String> stringsWithFiveLettersStartingWithA = strings
.stream()
.filter(s->s.length()==5)
.map(String::toUpperCase)
.filter(s->s.startsWith("A"))
.toList();
Submission from dan1st#7327
Want results from more Discord servers?
Add your server