<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <title>
      Static Factory Methods
     | Two 〈Foo〉s Walk into a 〈Bar〉</title>
  
  <updated>2009-08-22T17:38:00-05:00</updated>
  <author>
    <name>Chris Povirk</name>
    <email>beigetangerine@gmail.com</email>
    <uri>http://twofoos.org/</uri>
  </author>
  <link rel="alternate" type="application/xhtml+xml" hreflang="en" href="http://twofoos.org/content/static-factory-methods/"/>
  <link rel="self" type="application/atom+xml" href="http://twofoos.org/content/static-factory-methods/feed/"/>
  <rights>Copyright © 2003–2015 Chris Povirk.  All Rights Reserved.</rights>
  <id>http://twofoos.org/</id>
  <generator uri="http://twofoos.org/content/splat/" version="1.0">SPLAT</generator>
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
<entry>
    <updated>2009-08-22T17:38:00-05:00</updated>
    <summary>
            Update: significantly rewritten</summary>
    <title type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">Static Factory Methods</div>
    </title>
    <link rel="alternate" type="application/xhtml+xml" href="http://twofoos.org/content/static-factory-methods/#update_2009-08-22T17:38:00-05:00"/>
    <id>http://twofoos.org/content/static-factory-methods/#update_2009-08-22T17:38:00-05:00</id>
    <category term="effective-java"/>
    <category term="java"/>
    <content type="xhtml" xml:base="http://twofoos.org/">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <strong>significantly rewritten</strong>
        <div>

    <xhtml:h3>Book Summary</xhtml:h3>
    <div>
      <p>Static factory methods can:</p>
      <ul>
        <li>have names</li>
        <li>control when new instances are created</li>
        <li>return any subtype of their return type</li>
        <li>reduce the need to specify type parameters</li>
      </ul>
    </div>

    <xhtml:h3>Additional Points</xhtml:h3>
    <div>

    <p>Static factory methods can assist in safe publication and can allow for selective type bounds.</p>

      <xhtml:h4>Safe Publication</xhtml:h4>
      <div>

        <p>Sometimes you want to create an object and publish a reference to it at the same time.  Sometimes you publish the reference where other threads can see it.  The obvious approach is to handle it all in the constructor:</p>
<blockquote><pre>public final class Request {
  /** A request from some point in the past. */
  public static Request sampleRequest;

  private final Query query;
  private final User user;

  public Request(Query query, User user) {
    this.query = query;
    this.user = user;

    sampleRequest = this;
  }

  public Query getQuery() { return query; }
  public User getUser() { return user; }
}</pre></blockquote>

        <p>Notice that <code>sampleRequest</code> is not declared <code>volatile</code>.  The intent is to give up the guarantee that all threads will see the most recent value in favor of the speed of a non‐volatile write.  And it would work if only the code were slightly different:</p>

<blockquote><pre>public final class Request {
  /** A request from some point in the past. */
  public static Request sampleRequest;

  private final Query query;
  private final User user;
<ins style="display: inline; font-weight: bold;">
  public static Request create(Query query, User user) {
    Request request = new Request(query, user);
    sampleRequest = request;
    return request;
  }

  private</ins> Request(Query query, User user) {
    this.query = query;
    this.user = user;
  }

  public Query getQuery() { return query; }
  public User getUser() { return user; }
}</pre></blockquote>

        <p>Readers of an object published by the former code can behave nondeterministically.  But the latter code, by waiting until after the constructor to publish the reference (and by containing no non‐final fields), takes advantage of a feature of the memory model: the end‐of‐constructor "freeze."  This freeze ensures that the object appears fully initialized (and thus immutable) to other threads.  <a href="http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-2.html">Read Jeremy Manson's article on immutability</a>, and see also <a href="http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1218588162&amp;sr=8-1">Java Concurrency in Practice</a> pg. 41–42.</p>

        <p>What does this esoteric knowledge gain you?  Very little.  The reason is that examples like the above are rare.  In most cases, the act of publishing the reference is a <code>volatile</code> write or another synchronization action, such as adding the reference to a thread‐safe list of listeners.  Such actions guarantee that all steps performed before the publishing step are visible to all threads reading the reference.  The end‐of‐constructor freeze is superfluous.</p>

        <p>All this said, if you depend on others to write defensive code and they depend on you, you'll have problems.  Incomplete object initialization can be a security vulnerability:  An uninitialized "immutable" object might appear to contain an innocuous request during security checks, only to transform into a malicious one before execution.  <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6348370">Maybe spawning 0 processes is acceptable but 1,000,000 is not, or maybe 0 is a valid seed in a crypto algorithm but 1,000,000 is not.</a></p>

      </div>

      <xhtml:h4>Selective Type Bounds</xhtml:h4>
      <div>

        <xhtml:h5>The Problem</xhtml:h5>
        <div>

          <p>
          When parameterizing a class, I can choose to set bounds on the type parameter.  For example, <code>EnumSet</code> has type parameter <code>&lt;E extends Enum&lt;E&gt;&gt;</code>.  Or I can leave it unbounded: <code>HashSet</code> has type parameter <code>E</code>.
          </p>
          
          <p>
          Bounded or unbounded: What other options do I need?  Consider <code>TreeSet</code>.  <code>TreeSet</code> instances divide into two groups: those with a <code>Comparator</code> and those without.  When the caller provides a <code>Comparator</code>, the <code>TreeSet</code> can contain any kind of element supported by the <code>Comparator</code>.  Since I can define a <code>Comparator</code> for any type that I like, I can create a <code>TreeSet&lt;List&gt;</code>, a <code>TreeSet&lt;Rectangle&gt;</code>, or any other type, so long as I provide an appropriate <code>Comparator</code>.  On the other hand, when the caller does not provide a <code>Comparator</code>, the <code>TreeSet</code> can only contain elements that implement <code>Comparable</code> (specifically, elements that are <code>Comparable</code> to one another).  A <code>TreeSet&lt;List&gt;</code> without a <code>Comparator</code> will throw exceptions when it is used.
          </p>

          <p>
          The class's type parameter alone cannot provide us with the flexibility to solve this problem.  The result is two kinds of <code>TreeSet</code> constructors.  The first takes a <code>Comparator</code>.  As it should, it allows the caller to fill in any type for the type parameter, provided that it's compatible with the given <code>Comparator</code>.  The second type of constructor takes no <code>Comparator</code> argument, yet it, too, lets the client fill in any type for the type parameter.  This is broken, as it should allow only classes that implement <code>Comparable</code>.
          </p>

        </div>

        <xhtml:h5>The Solution</xhtml:h5>
        <div>

          <p>
          The fix is to remove <code>TreeSet</code>'s constructors in favor of static factory methods:
          </p>

<pre>&lt;E&gt; TreeSet&lt;E&gt; newTreeSet(Comparator&lt;? super E&gt; comparator);
&lt;E extends Comparable&lt;E&gt;&gt; TreeSet&lt;E&gt; newTreeSet();</pre>

          <p>
          As before, clients that provide a <code>Comparator</code> can create <code>TreeSet</code> instances for non‐<code>Comparable</code> types.  But now an attempt to create a <code>TreeSet</code> instance for a non‐<code>Comparable</code> type <em>without</em> supplying a <code>Comparator</code> will fail at compile time.
          </p>

          <p>
          Another option is to do away with the no‐arg constructor entirely and to force callers to pass <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Comparators.html#naturalOrder()"><code>Comparators.naturalOrder()</code></a>, a <code>Comparator&lt;C&gt;</code> for any <code>C</code> that extends <code>Comparable</code>, to the remaining constructor.  It won't take many calls to <code>new TreeSet&lt;T&gt;(Comparators.&lt;T&gt;naturalOrder())</code> to suggest that a static factory method is in order.
          </p>

          <p>
          Java trivia: Parameterized constructors are permitted:
          </p>

<pre>private &lt;T&gt; MyClass() { ... }</pre>

          <p>
          However, I have not found a way to use parameterized constructors to produce an equivalent solution.
          </p>

        </div>

        <xhtml:h5>Applications</xhtml:h5>
        <div>

          <p>
          <code>TreeSet</code> and other <code>SortedSet</code> implementations are the obvious example.  I could also imagine a scenario in which a class can serialize either (a) a class that knows how to convert itself to a string or (b) an arbitrary object plus an object that knows how to convert it to a string.  These cases are analogous the <code>SortedSet</code> case: <strong>Some objects can perform the necessary tasks themselves, while others require an external converter.</strong>  Static factory methods allow us to check uses of both types at compile time.
          </p>

<pre>&lt;E&gt; Serializer&lt;E&gt; newStringSerializer(Stringifier&lt;E&gt; stringifier);
&lt;E extends Stringifiable&gt; Serializer&lt;E&gt; newStringSerializer();</pre>

          <p>It's also possible to permit only a fixed set of type parameters:</p>

<pre>Serializer&lt;Integer&gt; newSerializer();
Serializer&lt;String&gt; newSerializer();</pre>

        </div>

      </div>

    </div>

  </div>
      </div>
    </content>
  </entry><entry>
    <updated>2008-08-12T21:20:00-05:00</updated>
    <summary>
            New: Static factory methods can do even more tricks.</summary>
    <title type="xhtml">
      <div xmlns="http://www.w3.org/1999/xhtml">Static Factory Methods</div>
    </title>
    <link rel="alternate" type="application/xhtml+xml" href="http://twofoos.org/content/static-factory-methods/#update_2008-08-12T21:20:00-05:00"/>
    <id>http://twofoos.org/content/static-factory-methods/#update_2008-08-12T21:20:00-05:00</id>
    <category term="effective-java"/>
    <category term="java"/>
    <content type="xhtml" xml:base="http://twofoos.org/">
      <div xmlns="http://www.w3.org/1999/xhtml">
        <strong>initial posting</strong>
        <div>
  

    <xhtml:h3>Book Summary</xhtml:h3>
    <div>
      <p>Static factory methods can:</p>
      <ul>
        <li>have names</li>
        <li>control when new instances are created</li>
        <li>return any subtype of their return type</li>
        <li>reduce the need to specify type parameters</li>
      </ul>
    </div>

    <xhtml:h3>Additional Points</xhtml:h3>
    <div>

    <p>Static factory methods can assist in safe publication and can allow for selective type bounds.</p>

      <xhtml:h4>Safe Publication</xhtml:h4>
      <div>

        <p>Sometimes you want to create an object and publish a reference to it at the same time.  Sometimes you publish the reference where other threads can see it.  The obvious approach is to handle it all in the constructor:</p>
<blockquote><pre>public final class Request {
  /** A request from some point in the past. */
  public static Request sampleRequest;

  private final Query query;
  private final User user;

  public Request(Query query, User user) {
    this.query = query;
    this.user = user;

    sampleRequest = this;
  }

  public Query getQuery() { return query; }
  public User getUser() { return user; }
}</pre></blockquote>

        <p>Notice that <code>sampleRequest</code> is not declared <code>volatile</code>.  The intent is to give up the guarantee that all threads will see the most recent value in favor of the speed of a non‐volatile write.  And it would work if only the code were slightly different:</p>

<blockquote><pre>public final class Request {
  /** A request from some point in the past. */
  public static Request sampleRequest;

  private final Query query;
  private final User user;
<ins style="display: inline; font-weight: bold;">
  public static Request create(Query query, User user) {
    Request request = new Request(query, user);
    sampleRequest = request;
    return request;
  }

  private</ins> Request(Query query, User user) {
    this.query = query;
    this.user = user;
  }

  public Query getQuery() { return query; }
  public User getUser() { return user; }
}</pre></blockquote>

        <p>Readers of an object published by the former code can behave nondeterministically.  But the latter code, by waiting until after the constructor to publish the reference (and by containing no non‐final fields), takes advantage of a feature of the memory model: the end‐of‐constructor "freeze."  This freeze ensures that the object appears fully initialized (and thus immutable) to other threads.  <a href="http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-2.html">Read Jeremy Manson's article on immutability</a>, and see also <a href="http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601/ref=pd_bbs_sr_1?ie=UTF8&amp;s=books&amp;qid=1218588162&amp;sr=8-1">Java Concurrency in Practice</a> pg. 41–42.</p>

        <p>What does this esoteric knowledge gain you?  Very little.  The reason is that examples like the above are rare.  In most cases, the act of publishing the reference is a <code>volatile</code> write or another synchronization action, such as adding the reference to a thread‐safe list of listeners.  Such actions guarantee that all steps performed before the publishing step are visible to all threads reading the reference.  The end‐of‐constructor freeze is superfluous.</p>

        <p>All this said, if you depend on others to write defensive code and they depend on you, you'll have problems.  Incomplete object initialization can be a security vulnerability:  An uninitialized "immutable" object might appear to contain an innocuous request during security checks, only to transform into a malicious one before execution.  <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6348370">Maybe spawning 0 processes is acceptable but 1,000,000 is not, or maybe 0 is a valid seed in a crypto algorithm but 1,000,000 is not.</a></p>

      </div>

      <xhtml:h4>Selective Type Bounds</xhtml:h4>
      <div>

        <xhtml:h5>The Problem</xhtml:h5>
        <div>

          <p>
          When parameterizing a class, I can choose to set bounds on the type parameter.  For example, <code>EnumSet</code> has type parameter <code>&lt;E extends Enum&lt;E&gt;&gt;</code>.  Or I can leave it unbounded: <code>HashSet</code> has type parameter <code>E</code>.
          </p>
          
          <p>
          Bounded or unbounded: What other options do I need?  Consider <code>TreeSet</code>.  <code>TreeSet</code> instances divide into two groups: those with a <code>Comparator</code> and those without.  When the caller provides a <code>Comparator</code>, the <code>TreeSet</code> can contain any kind of element supported by the <code>Comparator</code>.  Since I can define a <code>Comparator</code> for any type that I like, I can create a <code>TreeSet&lt;List&gt;</code>, a <code>TreeSet&lt;Rectangle&gt;</code>, or any other type, so long as I provide an appropriate <code>Comparator</code>.  On the other hand, when the caller does not provide a <code>Comparator</code>, the <code>TreeSet</code> can only contain elements that implement <code>Comparable</code> (specifically, elements that are <code>Comparable</code> to one another).  A <code>TreeSet&lt;List&gt;</code> without a <code>Comparator</code> will throw exceptions when it is used.
          </p>

          <p>
          The class's type parameter alone cannot provide us with the flexibility to solve this problem.  The result is two kinds of <code>TreeSet</code> constructors.  The first takes a <code>Comparator</code>.  As it should, it allows the caller to fill in any type for the type parameter, provided that it's compatible with the given <code>Comparator</code>.  The second type of constructor takes no <code>Comparator</code> argument, yet it, too, lets the client fill in any type for the type parameter.  This is broken, as it should allow only classes that implement <code>Comparable</code>.
          </p>

        </div>

        <xhtml:h5>The Solution</xhtml:h5>
        <div>

          <p>
          The fix is to remove <code>TreeSet</code>'s constructors in favor of static factory methods:
          </p>

<pre>&lt;E&gt; TreeSet&lt;E&gt; newTreeSet(Comparator&lt;? super E&gt; comparator);
&lt;E extends Comparable&lt;E&gt;&gt; TreeSet&lt;E&gt; newTreeSet();</pre>

          <p>
          As before, clients that provide a <code>Comparator</code> can create <code>TreeSet</code> instances for non‐<code>Comparable</code> types.  But now an attempt to create a <code>TreeSet</code> instance for a non‐<code>Comparable</code> type <em>without</em> supplying a <code>Comparator</code> will fail at compile time.
          </p>

          <p>
          Another option is to do away with the no‐arg constructor entirely and to force callers to pass <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Comparators.html#naturalOrder()"><code>Comparators.naturalOrder()</code></a>, a <code>Comparator&lt;C&gt;</code> for any <code>C</code> that extends <code>Comparable</code>, to the remaining constructor.  It won't take many calls to <code>new TreeSet&lt;T&gt;(Comparators.&lt;T&gt;naturalOrder())</code> to suggest that a static factory method is in order.
          </p>

          <p>
          Java trivia: Parameterized constructors are permitted:
          </p>

<pre>private &lt;T&gt; MyClass() { ... }</pre>

          <p>
          However, I have not found a way to use parameterized constructors to produce an equivalent solution.
          </p>

        </div>

        <xhtml:h5>Applications</xhtml:h5>
        <div>

          <p>
          <code>TreeSet</code> and other <code>SortedSet</code> implementations are the obvious example.  I could also imagine a scenario in which a class can serialize either (a) a class that knows how to convert itself to a string or (b) an arbitrary object plus an object that knows how to convert it to a string.  These cases are analogous the <code>SortedSet</code> case: <strong>Some objects can perform the necessary tasks themselves, while others require an external converter.</strong>  Static factory methods allow us to check uses of both types at compile time.
          </p>

<pre>&lt;E&gt; Serializer&lt;E&gt; newStringSerializer(Stringifier&lt;E&gt; stringifier);
&lt;E extends Stringifiable&gt; Serializer&lt;E&gt; newStringSerializer();</pre>

          <p>It's also possible to permit only a fixed set of type parameters:</p>

<pre>Serializer&lt;Integer&gt; newSerializer();
Serializer&lt;String&gt; newSerializer();</pre>

        </div>

      </div>

    </div>

  
  </div>
      </div>
    </content>
  </entry></feed>
