<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
		>
<channel>
	<title>Comments on: Mutable, Immutable and Generics</title>
	<atom:link href="http://codemonkeyism.com/mutable-immutable-and-generics/feed/" rel="self" type="application/rss+xml" />
	<link>http://codemonkeyism.com/mutable-immutable-and-generics/</link>
	<description></description>
	<lastBuildDate>Fri, 30 Jul 2010 06:49:07 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<item>
		<title>By: Aaron Faanes</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-226363</link>
		<dc:creator>Aaron Faanes</dc:creator>
		<pubDate>Tue, 03 Mar 2009 10:00:29 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-226363</guid>
		<description>(I&#039;m not familiar with the pattern suggested above specifically, so pardon if I&#039;m being redundant here :) )

Reading this post makes me think of a rather underappreciated (and apparently contentious?) class: String. String&#039;s immutability makes life in Java unbelievably easier. If String were mutable, it is no longer an implicitly safe key-value for hashing; you would have to enforce the de facto immutability through encapsulation. On the other hand, since it is mutable, you can use it freely.

Whenever String is modified, a new String is created that represents the requested State. The original remains the same, and the newly created string is not inflexible when it comes to apparent modification.

You could use this idea as an alternative to the above pattern. Whenever you want to change the state of the object, you clone the object, passing in the new state.

Of course, this has some dangers: String concatenation is very expensive as a consequence of this, since new String&#039;s must be created at every step. Of course, StringBuilder affords a truly mutable String that one could use, while still implementing the CharSequence interface that String does.

Because of the complementary nature of these two classes, the developer can intelligently, and easily, scale forward and backward the flexibility he wishes to present to the end-user. Furthermore, he can guarantee thread-safety (Which I think was mentioned in the comments) along with immutability of the parent (assuming this object has owners).

Something that I also appreciate, is that if you have immutable state, you can guarantee validity at all times: You&#039;re always guaranteed an object that has proper state. This is different from mutable objects, which have to go to alot more trouble to ensure their state.

As an example, imagine setting two points on a line. After you set the first point, but before you set the second, the object is in an invalid state. The state is valid to the Line class itself, but clients of that class would not be able to sensibly work with this value. This is the true essence of thread-safety, and I think it stems from solid, proactive design.

The Date class (And, ironically, the Point class) are two examples that I (and many others) think should have been immutable, but weren&#039;t. I imagine both were made mutable in the interests of performance and simplicity, but I think more damage was done in the long-run. This is especially true considering they could have followed the Foo/FooBuilder pattern, or the pattern discussed in the post above, instead.

All in all, favor immutability. :)</description>
		<content:encoded><![CDATA[<p>(I&#8217;m not familiar with the pattern suggested above specifically, so pardon if I&#8217;m being redundant here :) )</p>
<p>Reading this post makes me think of a rather underappreciated (and apparently contentious?) class: String. String&#8217;s immutability makes life in Java unbelievably easier. If String were mutable, it is no longer an implicitly safe key-value for hashing; you would have to enforce the de facto immutability through encapsulation. On the other hand, since it is mutable, you can use it freely.</p>
<p>Whenever String is modified, a new String is created that represents the requested State. The original remains the same, and the newly created string is not inflexible when it comes to apparent modification.</p>
<p>You could use this idea as an alternative to the above pattern. Whenever you want to change the state of the object, you clone the object, passing in the new state.</p>
<p>Of course, this has some dangers: String concatenation is very expensive as a consequence of this, since new String&#8217;s must be created at every step. Of course, StringBuilder affords a truly mutable String that one could use, while still implementing the CharSequence interface that String does.</p>
<p>Because of the complementary nature of these two classes, the developer can intelligently, and easily, scale forward and backward the flexibility he wishes to present to the end-user. Furthermore, he can guarantee thread-safety (Which I think was mentioned in the comments) along with immutability of the parent (assuming this object has owners).</p>
<p>Something that I also appreciate, is that if you have immutable state, you can guarantee validity at all times: You&#8217;re always guaranteed an object that has proper state. This is different from mutable objects, which have to go to alot more trouble to ensure their state.</p>
<p>As an example, imagine setting two points on a line. After you set the first point, but before you set the second, the object is in an invalid state. The state is valid to the Line class itself, but clients of that class would not be able to sensibly work with this value. This is the true essence of thread-safety, and I think it stems from solid, proactive design.</p>
<p>The Date class (And, ironically, the Point class) are two examples that I (and many others) think should have been immutable, but weren&#8217;t. I imagine both were made mutable in the interests of performance and simplicity, but I think more damage was done in the long-run. This is especially true considering they could have followed the Foo/FooBuilder pattern, or the pattern discussed in the post above, instead.</p>
<p>All in all, favor immutability. :)</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: lumpynose</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-82573</link>
		<dc:creator>lumpynose</dc:creator>
		<pubDate>Wed, 30 Apr 2008 21:41:56 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-82573</guid>
		<description>I&#039;m thinking that my asReadOnly doesn&#039;t need an argument and can simply return &#039;this&#039; and move the method to the ReadWritePoint class.</description>
		<content:encoded><![CDATA[<p>I&#8217;m thinking that my asReadOnly doesn&#8217;t need an argument and can simply return &#8216;this&#8217; and move the method to the ReadWritePoint class.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: lumpynose</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-82572</link>
		<dc:creator>lumpynose</dc:creator>
		<pubDate>Wed, 30 Apr 2008 21:35:36 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-82572</guid>
		<description>@stephan
I&#039;m thinking of simple value objects, so the conversions would be done via constructors that copy the object.  That&#039;s why I have the constructor ReadWritePoint(final ReadOnlyPoint point).  For going the other way, from ReadWritePoint to ReadOnlyPoint, you could have a method in ReadOnlyPoint that takes as its argument a ReadWritePoint and declares that it returns a ReadOnlyPoint;

public APIReadOnlyPoint asReadOnly(APIReadWritePoint point) {
    return(point);
}</description>
		<content:encoded><![CDATA[<p>@stephan<br />
I&#8217;m thinking of simple value objects, so the conversions would be done via constructors that copy the object.  That&#8217;s why I have the constructor ReadWritePoint(final ReadOnlyPoint point).  For going the other way, from ReadWritePoint to ReadOnlyPoint, you could have a method in ReadOnlyPoint that takes as its argument a ReadWritePoint and declares that it returns a ReadOnlyPoint;</p>
<p>public APIReadOnlyPoint asReadOnly(APIReadWritePoint point) {<br />
    return(point);<br />
}</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Maz</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-82540</link>
		<dc:creator>Maz</dc:creator>
		<pubDate>Wed, 30 Apr 2008 20:59:55 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-82540</guid>
		<description>@lumpynose
By definition protected members are not immutable even if the class itself does not support any setters. There could be subclasses modifying the members and your code could not rely an the immutibility.


So this raise the question of the meaning of immutable objects.
Immutable objects are under no condition modifiable. Best examples are the object representations of primitives (Integer, Boolean, etc.) and String.
JDK 1.3 could gain a huge performance gain by caching all strings and string creation and comparision was almost done in no time. 

It is really nice to see what is possible with generics as Stephan demonstrated, but for this case it would rather be advisable to keep things simple and just have two different classes: One mutable and one immutable if really needed.

public interface Point
{
   int getX(); int getY();
}

public class ImmutablePoint implements Point
{
  private int x;
  private int y;
  public int getX(){return x;}
  public int getY(){return y;}

  public ImmutablePoint(int x1, int y1)
  {
     x=x1;y=y1;
  }

  public MutablePoint mutablePoint()
  {
    return new MutablePoint(x,x);
  }
}

public class MutablePoint implements Point
{
  protected int x;
  protected int y;

  public int getX(){return x;}
  public int getY(){return y;}

  public void setX(int x1){x=x1;}
  public void setY(int y1){y=y1;}

  public MutablePoint(int x1, int y1)
  {
     x=x1;y=y1;
  }
  
  public ImmutablePoint immutablePoint()
  {
     // we could here also lookup in a cache for a immutable object representing the Point and return only this instance. 
     return new ImmutablePoint(x,y);
  }
}</description>
		<content:encoded><![CDATA[<p>@lumpynose<br />
By definition protected members are not immutable even if the class itself does not support any setters. There could be subclasses modifying the members and your code could not rely an the immutibility.</p>
<p>So this raise the question of the meaning of immutable objects.<br />
Immutable objects are under no condition modifiable. Best examples are the object representations of primitives (Integer, Boolean, etc.) and String.<br />
JDK 1.3 could gain a huge performance gain by caching all strings and string creation and comparision was almost done in no time. </p>
<p>It is really nice to see what is possible with generics as Stephan demonstrated, but for this case it would rather be advisable to keep things simple and just have two different classes: One mutable and one immutable if really needed.</p>
<p>public interface Point<br />
{<br />
   int getX(); int getY();<br />
}</p>
<p>public class ImmutablePoint implements Point<br />
{<br />
  private int x;<br />
  private int y;<br />
  public int getX(){return x;}<br />
  public int getY(){return y;}</p>
<p>  public ImmutablePoint(int x1, int y1)<br />
  {<br />
     x=x1;y=y1;<br />
  }</p>
<p>  public MutablePoint mutablePoint()<br />
  {<br />
    return new MutablePoint(x,x);<br />
  }<br />
}</p>
<p>public class MutablePoint implements Point<br />
{<br />
  protected int x;<br />
  protected int y;</p>
<p>  public int getX(){return x;}<br />
  public int getY(){return y;}</p>
<p>  public void setX(int x1){x=x1;}<br />
  public void setY(int y1){y=y1;}</p>
<p>  public MutablePoint(int x1, int y1)<br />
  {<br />
     x=x1;y=y1;<br />
  }</p>
<p>  public ImmutablePoint immutablePoint()<br />
  {<br />
     // we could here also lookup in a cache for a immutable object representing the Point and return only this instance.<br />
     return new ImmutablePoint(x,y);<br />
  }<br />
}</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: stephan</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-82457</link>
		<dc:creator>stephan</dc:creator>
		<pubDate>Wed, 30 Apr 2008 15:24:26 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-82457</guid>
		<description>@lumpynose: How do you get a ReadOnlyPoint from an ReadWritePoint and vice versa without a cast?</description>
		<content:encoded><![CDATA[<p>@lumpynose: How do you get a ReadOnlyPoint from an ReadWritePoint and vice versa without a cast?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: lumpynose</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-82437</link>
		<dc:creator>lumpynose</dc:creator>
		<pubDate>Wed, 30 Apr 2008 14:19:44 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-82437</guid>
		<description>Regarding Arnold&#039;s remark about using a proxy, what about the &quot;old fashioned&quot; way of using inheritance?  For example, see below.  What I like about this way is that you can have a method that returns either a ReadOnlyPoint or a ReadWritePoint, but declares that it returns a ReadOnlyPoint;

public APIReadOnlyPoint getPoint();

The users of that method know that they&#039;re getting a point that they cannot call the setters on, and the compiler won&#039;t let them.  No chance of exceptions being thrown.

public interface APIReadOnlyPoint {
    public T getX();

    public T getY();
}

public interface APIReadWritePoint extends APIReadOnlyPoint {
    public void setX(T x);

    public void setY(T y);
}

public class ReadOnlyPoint implements APIReadOnlyPoint {
    protected T x;
    protected T y;

    public ReadOnlyPoint(final T x, final T y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public T getX() {
        return x;
    }

    @Override
    public T getY() {
        return y;
    }
}

public final class ReadWritePoint extends ReadOnlyPoint implements
        APIReadWritePoint {
    public ReadWritePoint(final T x, final T y) {
        super(x, y);
    }

    public ReadWritePoint(final ReadOnlyPoint point) {
        super(point.getX(), point.getY());
    }

    @Override
    public void setX(final T x) {
        this.x = x;
    }

    @Override
    public void setY(final T y) {
        this.y = y;
    }
}</description>
		<content:encoded><![CDATA[<p>Regarding Arnold&#8217;s remark about using a proxy, what about the &#8220;old fashioned&#8221; way of using inheritance?  For example, see below.  What I like about this way is that you can have a method that returns either a ReadOnlyPoint or a ReadWritePoint, but declares that it returns a ReadOnlyPoint;</p>
<p>public APIReadOnlyPoint getPoint();</p>
<p>The users of that method know that they&#8217;re getting a point that they cannot call the setters on, and the compiler won&#8217;t let them.  No chance of exceptions being thrown.</p>
<p>public interface APIReadOnlyPoint {<br />
    public T getX();</p>
<p>    public T getY();<br />
}</p>
<p>public interface APIReadWritePoint extends APIReadOnlyPoint {<br />
    public void setX(T x);</p>
<p>    public void setY(T y);<br />
}</p>
<p>public class ReadOnlyPoint implements APIReadOnlyPoint {<br />
    protected T x;<br />
    protected T y;</p>
<p>    public ReadOnlyPoint(final T x, final T y) {<br />
        this.x = x;<br />
        this.y = y;<br />
    }</p>
<p>    @Override<br />
    public T getX() {<br />
        return x;<br />
    }</p>
<p>    @Override<br />
    public T getY() {<br />
        return y;<br />
    }<br />
}</p>
<p>public final class ReadWritePoint extends ReadOnlyPoint implements<br />
        APIReadWritePoint {<br />
    public ReadWritePoint(final T x, final T y) {<br />
        super(x, y);<br />
    }</p>
<p>    public ReadWritePoint(final ReadOnlyPoint point) {<br />
        super(point.getX(), point.getY());<br />
    }</p>
<p>    @Override<br />
    public void setX(final T x) {<br />
        this.x = x;<br />
    }</p>
<p>    @Override<br />
    public void setY(final T y) {<br />
        this.y = y;<br />
    }<br />
}</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: stephan</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-82265</link>
		<dc:creator>stephan</dc:creator>
		<pubDate>Wed, 30 Apr 2008 04:45:25 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-82265</guid>
		<description>@Maz: Of course, you are right. Good point.</description>
		<content:encoded><![CDATA[<p>@Maz: Of course, you are right. Good point.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Maz</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-82158</link>
		<dc:creator>Maz</dc:creator>
		<pubDate>Wed, 30 Apr 2008 00:00:57 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-82158</guid>
		<description>Hi Stephan,

The big advantage of immutable Objects is that they are immutable and their state will not change. Otherwise you have to take care about synchronization and the java memory model.
So your suggestion will break the immutable contract.

I would have expected to get a new mutable object by changing to mutable. By the I would also expect to be able to have the possibility to get a immutable version from the mutable object.

So the makeMutable method needs a modification:
# public MutablePoint makeMutable() {  
#       return new DefaultPoint(x,y);  
#    }

Anyway, the DefaultPoint ist not really an immutable object, so it is not the best practice to use this kind of code and rely on the immutablity of the point.</description>
		<content:encoded><![CDATA[<p>Hi Stephan,</p>
<p>The big advantage of immutable Objects is that they are immutable and their state will not change. Otherwise you have to take care about synchronization and the java memory model.<br />
So your suggestion will break the immutable contract.</p>
<p>I would have expected to get a new mutable object by changing to mutable. By the I would also expect to be able to have the possibility to get a immutable version from the mutable object.</p>
<p>So the makeMutable method needs a modification:<br />
# public MutablePoint makeMutable() {<br />
#       return new DefaultPoint(x,y);<br />
#    }</p>
<p>Anyway, the DefaultPoint ist not really an immutable object, so it is not the best practice to use this kind of code and rely on the immutablity of the point.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: stephan</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-81408</link>
		<dc:creator>stephan</dc:creator>
		<pubDate>Mon, 28 Apr 2008 16:24:07 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-81408</guid>
		<description>Yes, at least I can follow the argumentation.

With Qi4j I also would model the mutable state as a different concern.

http://www.jroller.com/rickard/entry/qi4j_status_report</description>
		<content:encoded><![CDATA[<p>Yes, at least I can follow the argumentation.</p>
<p>With Qi4j I also would model the mutable state as a different concern.</p>
<p><a href="http://www.jroller.com/rickard/entry/qi4j_status_report" rel="nofollow">http://www.jroller.com/rickard/entry/qi4j_status_report</a></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Arnold</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-81398</link>
		<dc:creator>Arnold</dc:creator>
		<pubDate>Mon, 28 Apr 2008 15:16:18 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-81398</guid>
		<description>Probably it&#039;s just a matter of taste. But  the mutable state of a bean could 
also be considered to be a cross cutting concern. 
Another approach could therefore be to implement this concern separately 
instead of as part of the bean itself.
Personally I would therefore favor the creation of a dynamically proxied Pointer
that wraps the original Pointer and throws an IllegalStateException when the settter
is called.  One could implement this approach by using java.lang.reflect.Proxy
But again, maybe it&#039;s just a matter of taste.</description>
		<content:encoded><![CDATA[<p>Probably it&#8217;s just a matter of taste. But  the mutable state of a bean could<br />
also be considered to be a cross cutting concern.<br />
Another approach could therefore be to implement this concern separately<br />
instead of as part of the bean itself.<br />
Personally I would therefore favor the creation of a dynamically proxied Pointer<br />
that wraps the original Pointer and throws an IllegalStateException when the settter<br />
is called.  One could implement this approach by using java.lang.reflect.Proxy<br />
But again, maybe it&#8217;s just a matter of taste.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: stephan</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-81337</link>
		<dc:creator>stephan</dc:creator>
		<pubDate>Mon, 28 Apr 2008 11:30:06 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-81337</guid>
		<description>Thanks :-)

point() is a factory (Fluent Interface style), see the method in DefaultPoint:

&lt;code&gt;
    public Point point(int x, int y) {  
         return new DefaultPoint(x,y);  
    }  
&lt;/code&gt;

For more code this could be packaged into a new Object &lt;code&gt;PointFactory&lt;/code&gt; oder &lt;code&gt;PointBuilder&lt;/code&gt;.</description>
		<content:encoded><![CDATA[<p>Thanks :-)</p>
<p>point() is a factory (Fluent Interface style), see the method in DefaultPoint:</p>
<p><code><br />
    public Point point(int x, int y) {<br />
         return new DefaultPoint(x,y);<br />
    }<br />
</code></p>
<p>For more code this could be packaged into a new Object <code>PointFactory</code> oder <code>PointBuilder</code>.</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Juanan</title>
		<link>http://codemonkeyism.com/mutable-immutable-and-generics/comment-page-1/#comment-81326</link>
		<dc:creator>Juanan</dc:creator>
		<pubDate>Mon, 28 Apr 2008 11:08:02 +0000</pubDate>
		<guid isPermaLink="false">http://stephan.reposita.org/archives/2008/04/28/mutable-immutable-and-generics/#comment-81326</guid>
		<description>great article! 

Just my 2 cents: I think that there&#039;s a little bug. Instead of:

 Point point = point(10,10);

it should be:

 Point point = new DefaultPoint(10,10);

isn&#039;t it?</description>
		<content:encoded><![CDATA[<p>great article! </p>
<p>Just my 2 cents: I think that there&#8217;s a little bug. Instead of:</p>
<p> Point point = point(10,10);</p>
<p>it should be:</p>
<p> Point point = new DefaultPoint(10,10);</p>
<p>isn&#8217;t it?</p>
]]></content:encoded>
	</item>
</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk (enhanced) (user agent is rejected)
Database Caching 4/23 queries in 0.021 seconds using disk

Served from: codemonkeyism.com @ 2010-07-30 12:46:01 -->