23 April 2012

Builder-Style DTO

MyDto is a Data Transfer Object that can be built using a chain of building calls.
You start by calling a factory method and then you add the info for MyDto step by step to the Builder. Each time this returns the builder, so you can chain the calls.
When you are finished, you call the build call, which returns the Data Transfer Object:

MyDto dto  = new MyDto.Builder()
       .name("Jef Blaaskop")
       .address("Antigoon 4")
The constructor of MyDto is private: you can only make it using the Builder. The Builder is an inner class of MyDto, so it can call the private constructor.
public class MyDto implements Serializable{
    private String address;
    private String name;
    private String city;

    private MyDto (String name,String address,String city) {
        this.city= city;
        this.address = address;
        this.name = name;

    private MyDto() {}

    public static class Builder{
        private MyDto dto;
            this.dto= new MyDto ();

        public Builder address(String address){
           // some checking
            return this;

        public Builder name(String name){
            if(name == null)
                throw new IllegalArgumentException("Anonymous not allowed");
            return this;

      public Builder city(String city){
           // some checking
            return this;

        public MyDto build(){
            return this.dto;
     }      // end Builder 
// remaining getters / setters ommitted
} // end MyDto