0

I am trying to create an immutable object using Jersey Java. But I don't know if the default constructor is useful or not in a big application. Can someone guide me on this.

This is my class :-

package com.jersey.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.pojomatic.Pojomatic;
import org.pojomatic.annotations.AutoProperty;

@XmlRootElement
@XmlType(name="todo")
@XmlAccessorType(XmlAccessType.FIELD)
@AutoProperty
public class Todo {

@XmlElement(name="summary")
private  final String summary;

@XmlElement(name="description")
private final String description;

public String getSummary() {
   return summary;
}

public String getDescription() {
   return description;
}

private Todo(){
   this(new Builder());
}

private Todo(Builder builder){
    this.summary = builder.summary;
    this.description = builder.description;
}

@Override 
public boolean equals(Object o) {
   return Pojomatic.equals(this, o);
}

@Override 
public int hashCode() {
  return Pojomatic.hashCode(this);
}

@Override 
public String toString() {
  return Pojomatic.toString(this);
}

public static class Builder{
    private String description;
    private String summary;

    public Builder summary(String summary){
        this.summary = summary;
        return this;
    }

    public Builder description(String description){
       this.description = description;
       return this;
    }

    public Todo build(){
       return new Todo(this);
    }
 }
}

So does the default constructor:-

 private Todo(){
   this(new Builder());
 }    

help in serialization/de-serialization or its of no use at all.

I don't know what effects will it have in a big application or should I not use it all.

Raj Hassani
  • 1,577
  • 1
  • 19
  • 26
  • Why did you implement a Builder? It's not required for an immutable object. Just declare the class fields as final and assign them in a normal constructor. – Stefaan Neyts Mar 19 '15 at 23:26
  • I am trying to use it because my class in the future will have many fields and as Joshua Bloch mentioned we should use Builder Pattern for Object creation if you have many fields in the class. – Raj Hassani Mar 19 '15 at 23:29
  • OK, fair enough to use a Builder pattern for that reason. But default constructor is obliged for JAXB, so I should add a protected default constructor which does nothing – Stefaan Neyts Mar 19 '15 at 23:40

0 Answers0