RSS Feed for This PostCurrent Article

Java Fluent Interface – Return Instance from Set Method

Normally we create a class with the constructor, set/get methods as below

public class Person {
    private String name;
    private Integer age;
    private String email;

    public Person() {
    }

    public Person(String name, Integer age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }  
}

To set the properties values, either we can use the constructor or set/get methods

public static void main(String[] args){
        Person p = new Person();
        p.setName("Jason");
        p.setEmail("[email protected]");
        p.setAge(20);
}

I don’t remember the name of this pattern, but nowadays I tend to do this.

public class Person {
    private String name;
    private Integer age;
    private String email;

    public Person() {
    }

    public Person(String name, Integer age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

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

    public String getEmail() {
        return email;
    }

    public Person setEmail(String email) {
        this.email = email;
        return this;
    }

    public static void main(String[] args){
        Person p = new Person();
        p.setName("jason").setEmail("[email protected]").setAge(20);
    }
}

UPDATE:

This is actually called fluent interface

A description of .NET implementation.


Trackback URL


RSS Feed for This Post2 Comment(s)

  1. Kedar Mhaswade | Dec 12, 2007 | Reply

    I think it’s called decorator pattern.

    But just curious — why wouldn’t you make this
    “value” class final and immutable? It solves all
    sorts of problems, especially with value classes.

    – Kedar

  2. IllishEsseply | Jan 3, 2009 | Reply

    qfqwwydumyzgogapwell, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch 😉

Sorry, comments for this entry are closed at this time.