<?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>Kevin&#039;s Life &#187; Readable</title>
	<atom:link href="http://blog.lckymn.com/tag/readable/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.lckymn.com</link>
	<description>IT, Java, Ubuntu, Linux</description>
	<lastBuildDate>Wed, 16 Jun 2010 14:08:36 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Method Chaining, to use, or not to use</title>
		<link>http://blog.lckymn.com/2009/06/30/method-chaining-to-use-or-not-to-use/</link>
		<comments>http://blog.lckymn.com/2009/06/30/method-chaining-to-use-or-not-to-use/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 17:33:28 +0000</pubDate>
		<dc:creator>Kevin</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Coding Style]]></category>
		<category><![CDATA[Command-Query Separation]]></category>
		<category><![CDATA[Debug]]></category>
		<category><![CDATA[Domain-Driven Design]]></category>
		<category><![CDATA[Eclipse]]></category>
		<category><![CDATA[Fluent Interface]]></category>
		<category><![CDATA[Formatter]]></category>
		<category><![CDATA[Formatting]]></category>
		<category><![CDATA[JavaBean]]></category>
		<category><![CDATA[Method Chaining]]></category>
		<category><![CDATA[Readable]]></category>

		<guid isPermaLink="false">http://blog.lckymn.com/?p=347</guid>
		<description><![CDATA[<p>It was a Gavin King&#8217;s book from which I first heard about <a href="http://en.wikipedia.org/wiki/Method_chaining" target="_blank">method chaining</a> since it is not that popular style in Java.</p>
<p>Bauer and King in their book entitled &#8216;Java Persistence with Hibernate&#8217; (2007), point out that method chaining is convenient in some cases and is more popular in <a href="http://en.wikipedia.org/wiki/Smalltalk" target="_blank">Smalltalk</a> than in <a href="http://en.wikipedia.org/wiki/Java_(programming_language)" target="_blank">Java</a> for Smalltalk, unlike Java, does not have <code>void</code> type. Thus when a method is invoked, it normally returns the object itself in <p style="border: 3px solid rgb(243, 197, 52); padding: 5px; background-color: rgb(254, 254, 184); width: 600px; text-align: center;">[...Continue reading <a href="http://blog.lckymn.com/2009/06/30/method-chaining-to-use-or-not-to-use/">Method Chaining, to use, or not to use</a>...]</p>]]></description>
			<content:encoded><![CDATA[<p>It was a Gavin King&#8217;s book from which I first heard about <a href="http://en.wikipedia.org/wiki/Method_chaining" target="_blank">method chaining</a> since it is not that popular style in Java.</p>
<p>Bauer and King in their book entitled &#8216;Java Persistence with Hibernate&#8217; (2007), point out that method chaining is convenient in some cases and is more popular in <a href="http://en.wikipedia.org/wiki/Smalltalk" target="_blank">Smalltalk</a> than in <a href="http://en.wikipedia.org/wiki/Java_(programming_language)" target="_blank">Java</a> for Smalltalk, unlike Java, does not have <code>void</code> type. Thus when a method is invoked, it normally returns the object itself in which the method is placed.</p>
<p>Although it is used to improve readability and to reduce the amount of source code, I didn&#8217;t really like this style as it can be less readable and might make code difficult to debug. How can the technique to improve readability make the code less readable? By less readable, I mean the code may possibly be unpredictable or make the programmer confused in some cases.</p>
<p>Let&#8217;s look at some example.</p>
<p>This is a simple JavaBean named <code>Item</code></p>
<pre class="brush: java;">
package com.lckymn.kevin.test.methodchaining;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public class Item
{
	private int id;
	private String name;

	public Item(int id, String name)
	{
		this.id = id;
		this.name = name;
	}

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	@Override
	public String toString()
	{
		return &quot;ID: &quot; + id + &quot;\n&quot; + &quot;Name: &quot; + name + &quot;\n&quot;;
	}
}
</pre>
<p>This is a Storage class designed to use method chaining.</p>
<pre class="brush: java;">
package com.lckymn.kevin.test.methodchaining;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public class Storage
{
	private List&lt;Item&gt; items;

	public Storage()
	{
		this.items = new ArrayList&lt;Item&gt;();
	}

	public Storage put(String name)
	{
		items.clear();
		return and(name);
	}

	public Storage and(String name)
	{
		items.add(new Item(name.hashCode(), name));
		return this;
	}

	public Item get(int index)
	{
		return items.get(index);
	}

	public List&lt;Item&gt; getAll()
	{
		return items;
	}
}
</pre>
<p>Now, let&#8217;s use it.</p>
<pre class="brush: java;">
package com.lckymn.kevin.test.methodchaining;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public final class MethodChainingTest
{
	public static void main(String[] args)
	{
		String name = new Storage().put(&quot;A&quot;).and(&quot;B&quot;).and(null).and(&quot;D&quot;).get(0).getName();
		System.out.println(&quot;Name: &quot; + name + &quot;\n&quot;);

		System.exit(0);
	}

}
</pre>
<p>What is this? It looks like instantiating a <code>Storage</code> object yet the end it assigns <code>String</code> value to <code>String</code> variable named <code>name</code>?</p>
<p>It seems confusing. First, instantiate <code>Storage</code>. Then call several methods in it. Finally call the method which returns a <code>String</code> value. However, the <code>Storage</code> class doesn&#8217;t even have any method returning the <code>String</code> value. It is the method in the <code>Item</code> class.</p>
<p>OK, move to the other problem that is difficulty in debuging.<br />
The example code above does not have any compile time error yet when it runs the result is </p>
<pre class="brush: bash; gutter: false;">
Exception in thread &quot;main&quot; java.lang.NullPointerException
	at com.lckymn.kevin.test.methodchaining.Storage.and(Storage.java:26)
	at com.lckymn.kevin.test.methodchaining.MethodChainingTest.main(MethodChainingTest.java:10)
</pre>
<p>The tenth line in the <code>MethodChainingTest.main</code> method is this.</p>
<pre class="brush: java; first-line: 10; highlight: [10];">
		String name = new Storage().put(&quot;A&quot;).and(&quot;B&quot;).and(null).and(&quot;D&quot;).get(0).getName();
</pre>
<p>The twenty-sixth line in the <code>Storage.and</code> method is this.</p>
<pre class="brush: java; first-line: 26; highlight: [26];">
		items.add(new Item(name.hashCode(), name));
</pre>
<p>So this line of the code causes <code>NullPointerException</code> but <code>and()</code> method is called three times in the tenth line of the <code>MethodChainingTest</code> class. Which one of these causes the error? In the example, it is very obvious that the <code>and()</code> method call with <code>null</code> parameter is the one. However, in real-life programme, it is usually much more difficult to find.</p>
<p>So, as already mentioned, I did not like using method chaining.  Then again there came a time when it was very convenient and useful to use method chaining. I found it very useful when I was making a XML generator programme for an Ajax application. I made it using <a href="http://en.wikipedia.org/wiki/JAXP" target="_blank">Java API for XML Processing (JAXP)</a>. It required to generate simple XML based on a given object so it might be too much to use <a href="http://en.wikipedia.org/wiki/XML_data_binding" target="_blank">XML data binding</a> frameworks and tools such as <a href="http://en.wikipedia.org/wiki/JAXB" target="_blank">Java Architecture for XML Binding (JAXB)</a> and <a href="http://en.wikipedia.org/wiki/XStream" target="_blank">XStream</a>. Although both JAXB and XStream are simple and easy to use and can be used to serialise objects, I wanted to have more control than what the framework provides. JAXP with <a href="http://en.wikipedia.org/wiki/Simple_API_for_XML" target="_blank">Simple API for XML (SAX)</a> parsing interface was just suitable for what I needed, yet it is not very pleasant to use the SAX interface. It uses ContentHandler interface when making XML contents and the following code is what it looks like when using it.</p>
<pre class="brush: java; gutter: false;">
contentHandler.startDocument();

AttributesImpl atts = new AttributesImpl();
atts.addAttribute(null, null, &quot;type&quot;, null, &quot;User&quot;);
contentHandler.startElement(null, null, &quot;users&quot;, atts);

atts.clear();
atts.addAttribute(null, null, &quot;id&quot;, null, &quot;kevin&quot;);
atts.addAttribute(null, null, &quot;surname&quot;, null, &quot;Lee&quot;);
atts.addAttribute(null, null, &quot;givenName&quot;, null, &quot;Kevin&quot;);
contentHandler.startElement(null, null, &quot;user&quot;, atts);
contentHandler.characters(&quot;Test value&quot;.toCharArray(), 0, &quot;Test value&quot;.length());
contentHandler.endElement(null, null, &quot;user&quot;);

atts.clear();
atts.addAttribute(null, null, &quot;id&quot;, null, &quot;john&quot;);
atts.addAttribute(null, null, &quot;surname&quot;, null, &quot;Doe&quot;);
atts.addAttribute(null, null, &quot;givenName&quot;, null, &quot;John&quot;);
contentHandler.startElement(null, null, &quot;user&quot;, atts);
contentHandler.characters(&quot;Blah Blah&quot;.toCharArray(), 0, &quot;Blah Blah&quot;.length());
contentHandler.endElement(null, null, &quot;user&quot;);

atts.clear();
atts.addAttribute(null, null, &quot;id&quot;, null, &quot;tom&quot;);
atts.addAttribute(null, null, &quot;surname&quot;, null, &quot;Smith&quot;);
atts.addAttribute(null, null, &quot;givenName&quot;, null, &quot;Tom&quot;);
contentHandler.startElement(null, null, &quot;user&quot;, atts);
contentHandler.characters(&quot;12345&quot;.toCharArray(), 0, &quot;12345&quot;.length());
contentHandler.endElement(null, null, &quot;user&quot;);

contentHandler.endElement(null, null, &quot;users&quot;);

contentHandler.endDocument();
</pre>
<p>As all I want was simple XML for an Ajax application, I had to type &#8216;<code>null</code>&#8216; many times as parameter values for namespace URI and local name which were definitely unnecessary for my programme. Since the data transfered through network need to be small, XML sent to the front-end Ajax application had better not have the data such as namespace and schema location information and so on.</p>
<p>However, what I all had was, as shown above, the ugly code which repeatedly calls same methods with many &#8216;null&#8217; parameters. So I tried to find a better way and eventually came up with that it might be a good idea to use method chaining.  Even so, there were still the two problems I mentioned.</p>
<p>The method chaining code example that I showed earlier is, in fact, a misuse of method chaining. That can be much better if it is used properly. After all, it is not the technique that makes the code less maintainable but how it is used that makes the code less maintainable.</p>
<p>Think about this. If a knife is used by a murderer, the result of using it would be a dead body while if it is used by a chef, the result would be a delicious meal unless the chef is the murderer. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  (I think I used this sentence when I had my presentation in the third year in my undergraduate days. The subject was about IT and ethics, and I was emphasising that technologies have nothing to do with ethics yet how we use these is important when it comes to ethics).</p>
<p>So, how can those two problems be solved? First of all, please don&#8217;t get me wrong. I am not saying that the way I am going to tell here is the best, but it is just what I do. That&#8217;s it.</p>
<p>I chose to implement <a href="http://en.wikipedia.org/wiki/Fluent_interface" target="_blank">fluent interface</a> yet with my own taste.</p>
<div class="txc-textbox" style="border: 3px solid rgb(243, 197, 52); padding: 10px; background-color: rgb(254, 254, 184);">
Cho, YoungHo (2008) in his article, &#8216;<a href="http://aeternum.egloos.com/1173825" target="_blank">Applicaiton of Domain-Driven Design 2.Aggregate and Repository #3</a>&#8216;, also says that although <a href="http://en.wikipedia.org/wiki/Fluent_interface" target="_blank">FLUENT INTERFACE</a> might violate the principle of <a href="http://en.wikipedia.org/wiki/Command-query_separation" target="_blank">COMMAND-QUERY SEPARATION</a> which enforces to separate the method to change the state of an object from the method to query the state, FLUENT INTERFACE using method chaining can enable the interface design to be more readable and easier to use.</p>
<p>If you can understand Korean and are interested in <a href="http://en.wikipedia.org/wiki/Domain-driven_design" target="_blank">Domain-Driven Design (DDD)</a>, his articles about DDD are really worth reading.<br />
<a href="http://aeternum.egloos.com/category/Domain-Driven%20Design" target="_blank">http://aeternum.egloos.com/category/Domain-Driven%20Design</a><br />
It is well written with appropriate example code and supporting theories and principles.
</div>
<p>So my tastes are<br />
1. The prefix &#8216;Fluent&#8217; shall be used to tell it is a fluent interface.<br />
e.g.)<br />
public interface FluentContentHandler<br />
public interface FluentStorage</p>
<p>2. <code>void</code> return type shall be used to stop method chaining if the method should not be used with other methods in the fluent interface or if it has some side-effect when using with other methods so that the programmer should be noticed it by void return type.<br />
e.g.)<br />
void endDoc()<br />
void finish()</p>
<p>3. Otherwise, all the methods shall return the type of interface itself, and the name of the normal methods which return the type of the interface itself shall begin with verb.<br />
e.g.)<br />
FluentContentHandler openElem(String qName)<br />
FluentContentHandler setText(String qName)<br />
FluentSaxAttributes create(String qName, String value)</p>
<p>OR<br />
The name of the method which must be used before the other methods shall begin with a verb.<br />
e.g.)<br />
FluentSaxAttributes create(String qName, String value)<br />
The name of the method which must be used after the method the name of which begins with a verb shall be an appropriate preposition or conjunction.<br />
e.g.)<br />
FluentSaxAttributes with(String qName, String value)<br />
FluentSaxAttributes and(String qName, String value)</p>
<p>4. If other types than the interface itself need to be returned, distinguishable method names shall be used. The name of the methods which return other type than the type of the interface itself shall begin with a preposition followed by a noun.<br />
e.g.)<br />
List toList()<br />
Map toMap()<br />
Collection toCollection()</p>
<p>I believe, these can help me to get over the first matter, and the code would be more readable as expected.</p>
<p>So let&#8217;s have a look at the new fluent interfaces for my XML generator programme.</p>
<pre class="brush: java;">
package com.lckymn.kevin.test.xml;

import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public interface FluentSaxContentHandler
{
	void startDoc() throws SAXException;

	void endDoc() throws SAXException;

	FluentSaxContentHandler openElem(String qName) throws SAXException;

	FluentSaxContentHandler openElem(String qName, FluentSaxAttributes attributes) throws SAXException;

	FluentSaxContentHandler setText(String text) throws SAXException;

	void closeElem(String qName) throws SAXException;
}
</pre>
<p>The programmer using this interface had better be aware of that <code>startDoc()</code> and <code>endDoc()</code> methods are to start and to end the XML document so use it once and therefore these return <code>void</code> type to warn. Similarly, <code>closeElem()</code> method the type of which is <code>void</code> closes the element with the name given as the parameter so the programmer had better stop method chaining here and open a new element with another method chaining.</p>
<pre class="brush: java;">
package com.lckymn.kevin.test.xml;

import org.xml.sax.helpers.AttributesImpl;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public interface FluentSaxAttributes
{
	FluentSaxAttributes create(String qName, String value);

	FluentSaxAttributes add(String qName, String value);

	AttributesImpl toAttributesImpl();
}
</pre>
<p>Since the <code>ContentHandler</code> requires <code>AttributesImpl</code> as attributes <code>toAttributesImpl()</code> method needs to return <code>AttributesImpl</code> and therefore its name consists of the preposition &#8216;to&#8217; and the noun &#8216;AttributesImpl&#8217;.</p>
<p>Now let&#8217;s use these.</p>
<pre class="brush: java; gutter: false;">
	contentHandler.startDoc();

	contentHandler.openElem(&quot;users&quot;, atts.create(&quot;type&quot;, &quot;User&quot;));

	contentHandler.openElem(&quot;user&quot;, atts.create(&quot;id&quot;, &quot;kevin&quot;).add(&quot;surname&quot;, &quot;Lee&quot;).add(&quot;givenName&quot;, &quot;Kevin&quot;)).setText(&quot;Test value&quot;).closeElem(&quot;user&quot;);
	contentHandler.openElem(&quot;user&quot;, atts.create(&quot;id&quot;, &quot;john&quot;).add(&quot;surname&quot;, &quot;Doe&quot;).add(&quot;givenName&quot;, &quot;John&quot;)).setText(&quot;Blah Blah&quot;).closeElem(&quot;user&quot;);
	contentHandler.openElem(&quot;user&quot;, atts.create(&quot;id&quot;, &quot;tom&quot;).add(&quot;surname&quot;, &quot;Smith&quot;).add(&quot;givenName&quot;, &quot;Tom&quot;)).setText(&quot;12345&quot;).closeElem(&quot;user&quot;);

	contentHandler.closeElem(&quot;users&quot;);

	contentHandler.endDoc();
</pre>
<p>It looks much simpler and readable than the previous code below.</p>
<pre class="brush: java; gutter: false;">
	contentHandler.startDocument();

	AttributesImpl atts = new AttributesImpl();
	atts.addAttribute(null, null, &quot;type&quot;, null, &quot;User&quot;);
	contentHandler.startElement(null, null, &quot;users&quot;, atts);

	atts.clear();
	atts.addAttribute(null, null, &quot;id&quot;, null, &quot;kevin&quot;);
	atts.addAttribute(null, null, &quot;surname&quot;, null, &quot;Lee&quot;);
	atts.addAttribute(null, null, &quot;givenName&quot;, null, &quot;Kevin&quot;);
	contentHandler.startElement(null, null, &quot;user&quot;, atts);
	contentHandler.characters(&quot;Test value&quot;.toCharArray(), 0, &quot;Test value&quot;.length());
	contentHandler.endElement(null, null, &quot;user&quot;);

	atts.clear();
	atts.addAttribute(null, null, &quot;id&quot;, null, &quot;john&quot;);
	atts.addAttribute(null, null, &quot;surname&quot;, null, &quot;Doe&quot;);
	atts.addAttribute(null, null, &quot;givenName&quot;, null, &quot;John&quot;);
	contentHandler.startElement(null, null, &quot;user&quot;, atts);
	contentHandler.characters(&quot;Blah Blah&quot;.toCharArray(), 0, &quot;Blah Blah&quot;.length());
	contentHandler.endElement(null, null, &quot;user&quot;);

	atts.clear();
	atts.addAttribute(null, null, &quot;id&quot;, null, &quot;tom&quot;);
	atts.addAttribute(null, null, &quot;surname&quot;, null, &quot;Smith&quot;);
	atts.addAttribute(null, null, &quot;givenName&quot;, null, &quot;Tom&quot;);
	contentHandler.startElement(null, null, &quot;user&quot;, atts);
	contentHandler.characters(&quot;12345&quot;.toCharArray(), 0, &quot;12345&quot;.length());
	contentHandler.endElement(null, null, &quot;user&quot;);

	contentHandler.endElement(null, null, &quot;users&quot;);

	contentHandler.endDocument();
</pre>
<p>Yet there is one more problem still left that is difficulty in debugging.</p>
<p>King and Bauer (2007) suggests that &#8220;it’s better to write each method invocation on a different line&#8221;.</p>
<p>So rewrite the code</p>
<pre class="brush: java; gutter: false;">
	contentHandler.startDoc();

	contentHandler.openElem(&quot;users&quot;, atts.create(&quot;type&quot;, &quot;User&quot;));

	contentHandler.openElem(&quot;user&quot;, atts.create(&quot;id&quot;, &quot;kevin&quot;)
			.add(&quot;surname&quot;, &quot;Lee&quot;)
			.add(&quot;givenName&quot;, &quot;Kevin&quot;))
			.setText(&quot;Test value&quot;)
			.closeElem(&quot;user&quot;);
	contentHandler.openElem(&quot;user&quot;, atts.create(&quot;id&quot;, &quot;john&quot;)
			.add(&quot;surname&quot;, &quot;Doe&quot;)
			.add(&quot;givenName&quot;, &quot;John&quot;))
			.setText(&quot;Blah Blah&quot;)
			.closeElem(&quot;user&quot;);
	contentHandler.openElem(&quot;user&quot;, atts.create(&quot;id&quot;, &quot;tom&quot;)
			.add(&quot;surname&quot;, &quot;Smith&quot;)
			.add(&quot;givenName&quot;, &quot;Tom&quot;))
			.setText(&quot;12345&quot;)
			.closeElem(&quot;user&quot;);

	contentHandler.closeElem(&quot;users&quot;);

	contentHandler.endDoc();
</pre>
<p>Now not only does it solve the problem in debugging but it is also even more readable. My problem solved! <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /><br />
Well, unfortunately there is one more problem. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>I am using Eclipse and it has a nice automatic formatting feature. So whenever I press SHIFT+CTRL+F, it automatically formats the code opened in the editor based on the format configuration. This means if I use that function, I lose the coding style of writing each method invocation on a different line as Eclipse formatter puts all the method on a different line together on one line. So do I have to reformat by myself after every automatic formatting? It&#8217;s really annoying. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> </p>
<p>Fortunately, a few changes in formatter configuration can solve this problem.</p>
<p>Click the &#8216;Window&#8217; menu -> &#8216;Preferences&#8217;</p>
<p>When the &#8216;Preferences&#8217; menu pops up<br />
-Expand the &#8216;Java&#8217; -> Expand the &#8216;Code Style&#8217; -> Select the &#8216;Fomatter&#8217;</p>
<p>-Click the &#8216;Edit&#8217; button on the top right-hand side.<br />
<div id="attachment_353" class="wp-caption alignnone" style="width: 693px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/06/formatter_configuration_01.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/06/formatter_configuration_01.jpg" alt="Expand the &#039;Java&#039; -&gt; Expand the &#039;Code Style&#039; -&gt; Select the &#039;Fomatter&#039; -&gt; Click the &#039;Edit&#039; button on the top right-hand side" title="Formatter Configuration for Method Chaining 01" width="683" height="740" class="size-full wp-image-353" /></a><p class="wp-caption-text">Expand the 'Java' -> Expand the 'Code Style' -> Select the 'Fomatter' -> Click the 'Edit' button on the top right-hand side</p></div></p>
<p>-The profile window appears -> Select the &#8216;Line Wrapping&#8217; -> Expand the &#8216;Function Calls&#8217; -> Select the &#8216;Qualified invocations&#8217; -> Select the &#8216;Wrap all elements, except first element if not necessary&#8217; as the &#8216;Line wrapping policy&#8217; -> Select the &#8216;Default indentation&#8217; as the &#8216;Indentation policy&#8217; -> Check the &#8216;Force split&#8217; -> Click the &#8216;OK&#8217; button.<br />
<div id="attachment_354" class="wp-caption alignnone" style="width: 757px"><a href="http://blog.lckymn.com/wp-content/uploads/2009/06/formatter_configuration_02.jpg"><img src="http://blog.lckymn.com/wp-content/uploads/2009/06/formatter_configuration_02.jpg" alt="Profile window appears -&gt; Select the &#039;Line Wrapping&#039; -&gt; Expand the &#039;Function Calls&#039; -&gt; Select the &#039;Qualified invocations&#039; -&gt; Select the &#039;Wrap all elements, except first element if not necessary&#039; as the &#039;Line wrapping policy&#039; -&gt; Select the &#039;Default indentation&#039; as the &#039;Indentation policy&#039; -&gt; Check the &#039;Force split&#039; -&gt; Click the &#039;OK&#039; button" title="Formatter Configuration for Method Chaining 02" width="747" height="834" class="size-full wp-image-354" /></a><p class="wp-caption-text">Profile window appears -> Select the 'Line Wrapping' -> Expand the 'Function Calls' -> Select the 'Qualified invocations' -> Select the 'Wrap all elements, except first element if not necessary' as the 'Line wrapping policy' -> Select the 'Default indentation' as the 'Indentation policy' -> Check the 'Force split' -> Click the 'OK' button</p></div></p>
<p>-Click the &#8216;OK&#8217; button to apply the changes.</p>
<p>Now, the Eclipse Java formatter formats the code, using method chaining, as what I want.</p>
<p>Finally, how can I improve my first example of method chaining?<br />
The Item class does not need to be changed.</p>
<p>Write the fluent interface, FluentStorage.</p>
<pre class="brush: java;">
package com.lckymn.kevin.test.fluentinterface;

import java.util.List;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public interface FluentStorage
{
	FluentStorage add(String name);

	List&lt;Item&gt; toList();
}
</pre>
<p>Write the class implements it.</p>
<pre class="brush: java;">
package com.lckymn.kevin.test.fluentinterface;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public class FluentListStorage implements FluentStorage
{
	private List&lt;Item&gt; items;

	public FluentListStorage()
	{
		items = new ArrayList&lt;Item&gt;();
	}

	@Override
	public FluentStorage add(String name)
	{
		items.add(new Item(name.hashCode(), name));
		return this;
	}

	@Override
	public List&lt;Item&gt; toList()
	{
		return items;
	}

}
</pre>
<p>Now use the fluent interface.</p>
<pre class="brush: java;">
package com.lckymn.kevin.test.fluentinterface;

import java.util.List;

/**
 * @author Lee, SeongHyun (Kevin)
 */
public final class MethodChainingTest
{
	public static void main(String[] args)
	{
		FluentStorage fluentStorage = new FluentListStorage().add(&quot;A&quot;)
				.add(&quot;B&quot;)
				.add(null)
				.add(&quot;D&quot;);

		List&lt;Item&gt; items = fluentStorage.toList();
		for (Item item : items)
		{
			System.out.println(item);
		}
		int howMany = items.size();
		System.out.println(&quot;There &quot; + (1 &lt; howMany ? &quot;are &quot; + howMany + &quot; items&quot; : &quot;is &quot; + howMany + &quot; item&quot;) + &quot; in the storage.&quot;);
		System.exit(0);
	}

}
</pre>
<p>When it runs, it displays the following error messages yet now I know that the fourteenth line causes the error.</p>
<pre class="brush: bash; gutter: false; highlight: [3];">
Exception in thread &quot;main&quot; java.lang.NullPointerException
	at com.lckymn.kevin.test.fluentinterface.FluentListStorage.add(FluentListStorage.java:21)
	at com.lckymn.kevin.test.fluentinterface.MethodChainingTest.main(MethodChainingTest.java:14)
</pre>
<p>The fourteenth line is this.</p>
<pre class="brush: java; first-line: 14;">
				.add(null)
</pre>
<p>So change it to</p>
<pre class="brush: java; first-line: 14;">
				.add(&quot;C&quot;)
</pre>
<p>I could finally have the correct result.</p>
<pre class="brush: plain; gutter: false;">
ID: 65
Name: A

ID: 66
Name: B

ID: 67
Name: C

ID: 68
Name: D

There are 4 items in the storage.
</pre>
<p>So method chaining, to use, or not to use? It&#8217;s all up to you. <img src='http://blog.lckymn.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </p>
<p><strong>References</strong><br />
Bauer, C. and King, G. 2007, <i>Java Persistence with Hibernate</i>, Manning Publications Co., New York.</p>
<p>Cho, Y. 2008, <i>Applicaiton of Domain-Driven Design 2. Aggregate and Repository #3</i>, viewed 29 June 2009, &lt;<a href="http://aeternum.egloos.com/1173825" target="_blank">http://aeternum.egloos.com/1173825</a>&gt;.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lckymn.com/2009/06/30/method-chaining-to-use-or-not-to-use/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
