OOP Tips: Methods Chaining

Method chaining is a nice way to reduce the verbosity of Java. It allows you to invoke several methods (one the same object instance) in one statement. It is actually more easy than you may think it is. You may already have encountered this pattern.

model.select(fields).where(conditions)

One neat trick that I do with my getters is to replace the void type by the class type and return the instance as show below

Consider the following class definition


class Person {
    private String name;
    private int age;

    public Person(){
    }

    //replace the usual void type by the class type        
    public Person setName(String name) {
        this.name = name;
        return this;
    }

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

    public int getAge(){
        return age;
    }	
}

Traditionally we normally call the setters like below


Person p = new Person();
p.setName("Adarsh Hasnah");
p.setAge(30);

However with method chaining, we can do this instead


Person p = new Person();
p.setName("Adarsh Hasnah").setAge(30);

We have now demonstrate how simple and easy it is to use method chaining

Archives

Adarsh Hasnah Written by: