immutability - Java Defensive copying and Immutable -


why must defensive copying in order achieve immutable class? @ code:

public final class emailmessage   {     private final string from;     private final string to;     private final string message;     private final date   date;      public emailmessage( string from, string to, string msg, date date )     {         this.to = to;         this.from = from;         this.message = msg;         this.date = new date(date.gettime());// instead of date;     }      public string getfrom()     {         return( );     }      public date getdate() {         return( new date( date.gettime() ); // instead of date     } } 

why won't immutable if didn't defensive copying?

in order achieve immutability must make copies of mutable objects passed constructor, , return copies mutable objects stored inside class, if any.

  • if not make copy of date passed you, caller can change date after object has been constructed, mutating it.
  • if not return copy getter of mutable object, callers can mutate object you, mutating object well.

in specific example, date class mutable. if yo skip copying in constructor, malicious code can this:

date d = new ... emailmessage msg = new emailmessage("lazy dog", "quick brown fox", "jump!", d); d.settime(d.gettime()+12345); // changes date inside msg 

if skip second copy, callers can this:

emailmessage msg = ... date d = msg.getdate(); d.settime(d.gettime()+12345); // changes date inside msg 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -