<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	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/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>John P Wood &#187; oo</title>
	<atom:link href="http://johnpwood.net/tag/oo/feed/" rel="self" type="application/rss+xml" />
	<link>http://johnpwood.net</link>
	<description>collection of thoughts...</description>
	<lastBuildDate>Thu, 10 May 2012 16:37:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Increase Design Flexibility by Separating Object Creation From Use</title>
		<link>http://johnpwood.net/2009/02/18/increase-design-flexibility-by-separating-object-creation-from-use/</link>
		<comments>http://johnpwood.net/2009/02/18/increase-design-flexibility-by-separating-object-creation-from-use/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 14:05:27 +0000</pubDate>
		<dc:creator>John Wood</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[oo]]></category>

		<guid isPermaLink="false">http://johnpwood.net/?p=321</guid>
		<description><![CDATA[I just finished reading Emergent Design, by Scott Bain. Overall, I thought it was a pretty good book that touched on some important concepts in software design. I&#8217;ve read about [...]]]></description>
			<content:encoded><![CDATA[<p>I just finished reading Emergent Design, by Scott Bain.  Overall, I thought it was a pretty good book that touched on some important concepts in software design.  I&#8217;ve read about one particular concept covered in the book a few times before, but the value of it didn&#8217;t sink in until I read Emergent Design.  This concept states that code that creates an object should be separate from code that uses the object.</p>
<p>Separating code that creates an object from the code that uses the object results in a much more flexible design, which is easier to change.  Creating this separation is also very easy to do.  By simply avoiding a call to the <code>new</code> operator in the &#8220;client&#8221; code for the particular object you wish to instantiate, you are able to evolve your code to adjust to a variety of changes, most of which require no changes in the code that uses the object.  Let&#8217;s walk through an example.</p>
<p>Let&#8217;s say we have a logging class, named <code>Logger</code>, that we use to log messages from our application.  The class is pretty simple, and looks something like this.</p>
<pre class="brush:java">
public class Logger {
    private static final String logFileName = "application.log";
    private FileWriter fileWriter;
    private Class<?> from;

    public Logger(Class<?> from) {
        this.from = from;

        try {
            fileWriter = new FileWriter(logFileName, true);
        } catch (IOException e) {
            throw new RuntimeException("Log file '" + logFileName +
                    "' could not be opened for writing.", e);
        }
    }

    public void log(String message) {
        try {
            fileWriter.write(
                from.getCanonicalName() + ": " + message + "\n");
            fileWriter.flush();
        } catch (IOException e) {
            System.err.println("Writing to the log file failed");
            e.printStackTrace();
        }
    }
}
</pre>
<p>In our application, we would typically use the <code>Logger</code> class like this:</p>
<pre class="brush:java">
Logger logger = new Logger(MyClass.class);
logger.log("Some message");
</pre>
<p>I think this is pretty typical, and seems to be the default pattern.  Create the object that you need, and then use it.  Simple and straightforward.  However, the simplicity comes at the price of limited flexibility.  For example, what if I wanted to limit the <code>Logger</code> class to only having one instance?  Or, what if I wanted to start logging some messages to the database, and some to the file system?  By combining the code that creates the object with the code that uses the object, we&#8217;ve greatly limited the ways in which we can evolve our design without affecting existing &#8220;client&#8221; code.  Sure, we can work our way out of it, but since the <code>Logger</code> is a very popular class used by almost every other class in the system, it will require a lot of work to change.</p>
<p>So, how can we avoid this?  How can we effectively encapsulate the creation of the object from the code that uses it?  The very first &#8220;tip&#8221; in Effective Java, by Joshua Bloch, is to prefer static builder methods over constructors.  Joshua suggests this for the same reasons Scott suggests separating code that creates the object from code that uses the object in Emergent Design.  Instead of making your clients use the <code>new</code> operator to create instances of your object, provide them with a static builder method to do so.  </p>
<pre class="brush:java">
    public static Logger getInstance(Class<?> from) {
        return new Logger(from);
    }

    protected Logger(Class<?> from) {
        this.from = from;

        try {
            fileWriter = new FileWriter(logFileName, true);
        } catch (IOException e) {
            throw new RuntimeException("Log file '" + logFileName +
                    "' could not be opened for writing.", e);
        }
    }
</pre>
<p>Note that I changed the scope of <code>Logger</code>&#8216;s constructor from public to protected.  This will discourage other classes outside of the logging package from using it, while leaving the <code>Logger</code> class open for subclassing.  With this new method in place, users of this class can now create an instance by doing the following.</p>
<pre class="brush:java">
Logger logger = Logger.getInstance(MyClass.class);
logger.log("Some message");
</pre>
<p>It seems silly to provide a method that simply calls <code>new</code>.  But, doing so adds so much flexibility to the design, that Scott considers it a &#8220;practice&#8221;, or something he does every time without even thinking about it.  Abandoning the constructor also opens a few doors.  You are no longer required to return an instance of that specific class, giving you the freedom return any object of that type.  You don&#8217;t always have to return a new instance, allowing you to implement a cache, or a singleton.  You can use this flexibility to your advantage when evolving your design.  Let&#8217;s see how.</p>
<p>Let&#8217;s say we get a request from our accounting department to log messages from code that deals with financial transactions (conveniently located in the <code>net.johnpwood.financial</code> package) to the database.  This sounds like the birth of a new type of logger.  Because clients are not using the <code>new</code> operator to create new instances of the <code>Logger</code> class, we can easily evolve <code>Logger</code> into an abstract class, keeping the static <code>getInstance()</code> method as the factory method for the <code>Logger</code> class hierarchy.  After we have the abstract class, we can create two new subclasses to implement the individual behavior.  All of this with no change to how the client uses the logging functionality.</p>
<p>Because the filesystem logger and the database logger don&#8217;t have too much in common, the <code>Logger</code> class has been slimmed down quite a bit.  What remains is the interface for the <code>Logger</code> subtypes, defined via the abstract <code>log()</code> method, and a factory method to create the proper logger, which is implemented in <code>getInstance()</code>.</p>
<pre class="brush:java">
public abstract class Logger {

    public static Logger getInstance(Class<?> from) {
        if (from.getCanonicalName().startsWith(
                "net.johnpwood.financial")) {
            return DatabaseLogger.getInstance(from);
        } else {
            return FilesystemLogger.getInstance(from);
        }
    }

    protected Logger() {}
    public abstract void log(String message);
}
</pre>
<p>We now have two distinct classes that handle logging transactions.  <code>FilesystemLogger</code>, which contains most of the old <code>Logger</code> code, and <code>DatabaseLogger</code>.  <code>FilesystemLogger</code> should look pretty familiar.</p>
<pre class="brush:java">
public class FilesystemLogger extends Logger {
    private static final String logFileName = "application.log";
    private FileWriter fileWriter;
    private Class<?> from;

    public static FilesystemLogger getInstance(Class<?> from) {
        return new FilesystemLogger(from);
    }

    protected FilesystemLogger(Class<?> from) {
        this.from = from;

        try {
            fileWriter = new FileWriter(logFileName, true);
        } catch (IOException e) {
            throw new RuntimeException("Log file '" + logFileName +
                    "' could not be opened for writing.", e);
        }
    }

    @Override
    public void log(String message) {
        try {
            fileWriter.write(
                from.getCanonicalName() + ": " + message + "\n");
            fileWriter.flush();
        } catch (IOException e) {
            System.err.println("Writing to the log file failed");
            e.printStackTrace();
        }
    }
}
</pre>
<p><code>DatabaseLogger</code> is also pretty simple, since I didn&#8217;t bother to implement any of the hairy database code (doesn&#8217;t help to illustrate the point&#8230;and I&#8217;m lazy).</p>
<pre class="brush:java">
public class DatabaseLogger extends Logger {
    private Class<?> from;

    public static DatabaseLogger getInstance(Class<?> from) {
        return new DatabaseLogger(from);
    }

    protected DatabaseLogger(Class<?> from) {
        this.from = from;
        establishDatabaseConnection();
    }

    @Override
    public void log(String message) {
        LoggerDataObject dataObject =
            new LoggerDataObject(from, message);
        dataObject.save();
    }

    private void establishDatabaseConnection() {
        // Connect to the database
    }
}
</pre>
<p>We&#8217;ve significantly changed how the <code>Logger</code> works, and the client is totally oblivious to the changes.  The client code continues to use the <code>Logger</code> as it did before, and everything just works.  Pretty sweet, eh?  </p>
<p>As you can imagine, there are many other ways you can evolve your design if you have this separation of creation and use.  If we need to create a <code>MockLogger</code> for testing purposes, it can be created in <code>Logger.getInstance()</code> along with the other <code>Logger</code> implementations.  The client would never know that it is using a mock.  If we ended up creating 10 different loggers, it would be trivial to have <code>Logger.getInstance()</code> delegate the creation of the proper <code>Logger</code> instance to a factory, moving the creation logic out of the <code>Logger</code> class.  Again, no changes to the client.</p>
<p>Separating creation from use also allows you to easily evolve your class into a singleton (or any other pattern that controls the number of instances created).  This doesn&#8217;t make much sense for <code>Logger</code>, since each unique <code>Logger</code> instance contains state.  However, it does make sense for some classes.  Evolving your class into a singleton simply requires a static instance variable on the class containing the instance of the singleton object, and an implementation of <code>getInstance()</code> that returns the singleton instance.  If clients have already been using the <code>getInstance()</code> method to get an instance of the class, then no change would be required on their end.  Here&#8217;s an example:</p>
<pre class="brush:java">
public class SomeOtherClass {
    private static SomeOtherClass instance = new SomeOtherClass();

    public static SomeOtherClass getInstance() {
        return instance;
    }

    private SomeOtherClass() {}
}
</pre>
<p>It is worth pointing out that static builder methods are not the only way to achieve this separation.  Dependency injection frameworks like Spring and Guice do all of this for you.  They take on the responsibility of creating the objects, and getting the instances to the code that uses them.  If you are a disciplined developer, and never &#8220;cheat&#8221; by instantiating the objects directly, then all of the same benefits outlined above apply when using a dependency injection framework.</p>
<p>Like everything in life, there are cons that go along with the pros.  Separating the code that creates an object from the code that uses the object is not the default pattern.  It is not the norm.  It will take time for you and your co-workers to get comfortable with this pattern.  API documentation tools don&#8217;t &#8220;call out&#8221; static builder methods like they do constructors.  This could have an effect on anybody using your library.  Dependency injection frameworks take the creation of objects completely out of your code, moving it to some magical, mysterious land where things just happen, somehow.  This also can take some time to get used to, especially for those new to the concept.</p>
<p>However, I feel that the benefits of separating creation from use far outweigh the drawbacks.  </p>
<p>In our field, change is a constant.  As a profession, we&#8217;re gradually learning to stop fighting change, and to start accepting it.  This means designing for change.  Doing so makes everybody&#8217;s life easier, from the customer to the developer.  Separating creation from use is one, quick way we can increase the flexibility of our design, with very little up front cost.</p>
<p>Thanks to <a href="http://mmurthy.com">Mahesh Murthy</a> for reviewing this post.</p>
]]></content:encoded>
			<wfw:commentRss>http://johnpwood.net/2009/02/18/increase-design-flexibility-by-separating-object-creation-from-use/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

