title: Immutable beans in Java
body: <p>I am very curious about the possibility of providing immutability for java beans (by beans here I mean classes with an empty constructor providing getters and setters for members).    Clearly these classes are not immutable and where they are used to transport values from the data layer this seems like a real problem.</p>
  
  <p>One approach to this problem has been mentioned here in StackOverflow called "Immutable object pattern in C#" where the object is frozen once fully built.  I have an alternative approach and would really like to hear people's opinions on it.</p>
  
  <p>The pattern involves two classes Immutable and Mutable where Mutable and Immutable both implement an interface which provides non-mutating bean methods.</p>
  
  <p>For example</p>
  
  <pre><code>public interface DateBean {
      public Date getDate();
      public DateBean getImmutableInstance();
      public DateBean getMutableInstance();
  }
  
  public class ImmutableDate implements DateBean {
      private Date date;
  
  ImmutableDate(Date date) {
      this.date = new Date(date.getTime());
  }
  
  public Date getDate() {
      return new Date(date.getTime());
  }
  
      public DateBean getImmutableInstance() {
          return this;
      }
  
      public DateBean getMutableInstance() {
          MutableDate dateBean = new MutableDate();
          dateBean.setDate(getDate());
          return dateBean;
      }
  }
  
  public class MutableDate implements DateBean {
      private Date date;
  
  public Date getDate() {
      return date;
  }
  
  public void setDate(Date date) {
      this.date = date;
  }
  
  public DateBean getImmutableInstance() {
      return new ImmutableDate(this.date);
  }
  
      public DateBean getMutableInstance() {
          MutableDate dateBean = new MutableDate();
          dateBean.setDate(getDate());
          return dateBean;
      }
  }
  </code></pre>
  
  <p>This approach allows the bean to be constructed using reflection (by the usual conventions) and also allows us to convert to an immutable variant at the nearest opportunity.  Unfortunately there is clearly a large amount of boilerplate per bean.</p>
  
  <p>I am very interested to hear other people's approach to this issue.  (My apologies for not providing a good question, which can be answered rather than discussed :)</p>