<?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>Mea Cup O' Jo &#187; Java</title>
	<atom:link href="http://dev.bostone.us/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://dev.bostone.us</link>
	<description>Jump Right Ahead In My Web</description>
	<lastBuildDate>Mon, 12 Dec 2011 18:30:30 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Android: display orientation in phones vs tablets</title>
		<link>http://dev.bostone.us/2011/06/30/android-display-orientation-in-phones-vs-tablets/</link>
		<comments>http://dev.bostone.us/2011/06/30/android-display-orientation-in-phones-vs-tablets/#comments</comments>
		<pubDate>Thu, 30 Jun 2011 15:57:20 +0000</pubDate>
		<dc:creator>bo</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dev.bostone.us/?p=386</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<p>If you have 2 layouts (portrait and landscape) and the order seems to be reversed on the tablet then switch to using <strong>getRotation </strong>instead of deprecated <strong>getOrientation</strong>. Something like this</p>
<pre class="brush: java; title: ; notranslate">
    private void setLayout() {
        // Get display for detecting the phone orientation
        final Display display = ((WindowManager) getSystemService(
            WINDOW_SERVICE)).getDefaultDisplay();
        if (display.getRotation() == Surface.ROTATION_0 ||
            display.getRotation() == Surface.ROTATION_180) {
            setContentView(R.layout.home);
        } else {
            setContentView(R.layout.home_l);
        }
    }
</pre>
<p>P.S.<br />
Actually, ignore code above it will not work. All you really need to do is to detect what is larger &#8211; height or width and adjust layout accordingly</p>
<pre class="brush: java; title: ; notranslate">
    private void setLayout() {
        // Get display for detecting the phone orientation
        final Display display = ((WindowManager)
             getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        final boolean isTall = display.getHeight() &gt; display.getWidth();
        setContentView(isTall ? R.layout.home : R.layout.home_l);
    }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dev.bostone.us/2011/06/30/android-display-orientation-in-phones-vs-tablets/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Use Yaml with Spring to load properties</title>
		<link>http://dev.bostone.us/2011/02/03/use-yaml-with-spring-to-load-properties/</link>
		<comments>http://dev.bostone.us/2011/02/03/use-yaml-with-spring-to-load-properties/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 22:39:50 +0000</pubDate>
		<dc:creator>bo</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://dev.bostone.us/?p=378</guid>
		<description><![CDATA[I was surprised to find that Spring framework doesn&#8217;t have Yaml-based PropertyPlaceholderConfigurer to load nested properties from Yaml property file. After some investigation turned out that instead of writing YamlPropertyPlaceholderConfigurer it is sufficient to write Yaml implementation of PropertiesPersister.
Here&#8217; show your applicationContext.xml (snippet) will look

    &#60;bean id=&#34;propertyConfigurer&#34; class=&#34;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&#34;&#62;
     [...]]]></description>
			<content:encoded><![CDATA[<p>I was surprised to find that Spring framework doesn&#8217;t have Yaml-based PropertyPlaceholderConfigurer to load nested properties from Yaml property file. After some investigation turned out that instead of writing YamlPropertyPlaceholderConfigurer it is sufficient to write Yaml implementation of PropertiesPersister.</p>
<p>Here&#8217; show your applicationContext.xml (snippet) will look</p>
<pre class="brush: xml; title: ; notranslate">
    &lt;bean id=&quot;propertyConfigurer&quot; class=&quot;org.springframework.beans.factory.config.PropertyPlaceholderConfigurer&quot;&gt;
        &lt;property name=&quot;locations&quot;&gt;
            &lt;value&gt;file:///C:/foo/properties.yaml&lt;/value&gt;
        &lt;/property&gt;
        &lt;property name=&quot;propertiesPersister&quot; ref=&quot;persister&quot;&gt;&lt;/property&gt;
    &lt;/bean&gt;
    &lt;bean id=&quot;persister&quot; class=&quot;com.foo.utils.YamlPropertiesPersister&quot;&gt;&lt;/bean&gt;
</pre>
<p>And here&#8217;s bare-bone PropertiesPersister implementation using SnakeYaml as parser</p>
<pre class="brush: java; title: ; notranslate">
public class YamlPropertiesPersister implements PropertiesPersister {
    @Override
    public void load(Properties props, InputStream is) throws IOException {
        load(props, new InputStreamReader(is));
    }

    /**
     * We want to traverse map representing Yaml object and each time we will find String:String value pair we want to
     * save it as Property. As we are going deeper into map we generate a compound key as path-like String
     *
     * @param props
     * @param reader
     * @throws IOException
     * @see org.springframework.util.PropertiesPersister#load(java.util.Properties, java.io.Reader)
     */
    @Override
    public void load(Properties props, Reader reader) throws IOException {
        Yaml yaml = CollectorUtils.instanceOfYaml();
        Map&lt;String, Object&gt; map = (Map&lt;String, Object&gt;) yaml.load(reader);
        // now we can populate supplied props
        assignProperties(props, map, null);
    }

    /**
     * @param props
     * @param map
     */
    public void assignProperties(Properties props, Map&lt;String, Object&gt; map, String path) {
        for (Entry&lt;String, Object&gt; entry : map.entrySet()) {
            String key = entry.getKey();
            if (StringUtils.isNotEmpty(path))
                key = path + &quot;.&quot; + key;
            Object val = entry.getValue();
            if (val instanceof String) {
                // see if we need to create a compound key
                props.put(key, val);
            } else if (val instanceof Map) {
                assignProperties(props, (Map&lt;String, Object&gt;) val, key);
            }
        }
    }

    @Override
    public void store(Properties props, OutputStream os, String header) throws IOException {
        throw new NotImplementedException(&quot;Current implementation is a read-only&quot;);
    }

    @Override
    public void store(Properties props, Writer writer, String header) throws IOException {
        throw new NotImplementedException(&quot;Current implementation is a read-only&quot;);
    }

    @Override
    public void loadFromXml(Properties props, InputStream is) throws IOException {
        throw new NotImplementedException(&quot;Use DefaultPropertiesPersister if you want to read/write XML&quot;);
    }

    @Override
    public void storeToXml(Properties props, OutputStream os, String header) throws IOException {
        throw new NotImplementedException(&quot;Use DefaultPropertiesPersister if you want to load/store to XML&quot;);
    }

    @Override
    public void storeToXml(Properties props, OutputStream os, String header, String encoding) throws IOException {
        throw new NotImplementedException(&quot;Use DefaultPropertiesPersister if you want to read/write XML&quot;);
    }
}
</pre>
<p>And as an added bonus, here&#8217;s how you create Yaml instance with SnakeYaml</p>
<pre class="brush: java; title: ; notranslate">
    public static Yaml instanceOfYaml() {
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        options.setDefaultScalarStyle(ScalarStyle.DOUBLE_QUOTED);
        final Yaml yaml = new Yaml(new Loader(), new Dumper(options), new Resolver() {
            /**
             * @see org.yaml.snakeyaml.resolver.Resolver#addImplicitResolvers()
             */
            @Override
            protected void addImplicitResolvers() {
                addImplicitResolver(Tag.BOOL, BOOL, &quot;yYnNtTfFoO&quot;);
                // disable resolving of floats and integers
                // addImplicitResolver(Tags.FLOAT, FLOAT, &quot;-+0123456789.&quot;);
                // addImplicitResolver(Tag.INT, INT, &quot;-+0123456789&quot;);
                addImplicitResolver(Tag.MERGE, MERGE, &quot;&lt;&quot;);
                addImplicitResolver(Tag.NULL, NULL, &quot;~nN&#92;&#48;&quot;);
                addImplicitResolver(Tag.NULL, EMPTY, null);
                addImplicitResolver(Tag.TIMESTAMP, TIMESTAMP, &quot;0123456789&quot;);
                addImplicitResolver(Tag.VALUE, VALUE, &quot;=&quot;);
            }
        });
        return yaml;
    }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dev.bostone.us/2011/02/03/use-yaml-with-spring-to-load-properties/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>GOTO Java</title>
		<link>http://dev.bostone.us/2010/02/27/goto-java/</link>
		<comments>http://dev.bostone.us/2010/02/27/goto-java/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 22:39:11 +0000</pubDate>
		<dc:creator>bo</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://dev.bostone.us/?p=327</guid>
		<description><![CDATA[Here&#8217;s the scenario:

Loop through the list and for each slot

Compare current value with the given value
If match is found modify current item and break the loop


If the given value wasn&#8217;t find in the loop add it to the list

Turns out breaking out of loops using labels also works for curly block of code so the [...]]]></description>
			<content:encoded><![CDATA[<p>Here&#8217;s the scenario:</p>
<ol>
<li>Loop through the list and for each slot
<ol>
<li>Compare current value with the given value</li>
<li>If match is found modify current item and break the loop</li>
</ol>
</li>
<li>If the given value wasn&#8217;t find in the loop add it to the list</li>
</ol>
<p>Turns out breaking out of loops using labels also works for curly block of code so the solution is below</p>
<pre type="code" class="java">
List<Foo> list = getFromSomewhere();
Foo foo = whatever();
gotu: {
    for (Foo f : list) {
        if ( f.equals(foo)) {
            f.setBlah(foo.getBlah()); // blah is not used in compare()
            break gotu;
       }
    }
// only want to execute the following if the loop was never broken
list.add(foo);
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dev.bostone.us/2010/02/27/goto-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing JUnit friendly static code</title>
		<link>http://dev.bostone.us/2009/08/17/writing-junit-friendly-static-code/</link>
		<comments>http://dev.bostone.us/2009/08/17/writing-junit-friendly-static-code/#comments</comments>
		<pubDate>Mon, 17 Aug 2009 17:29:41 +0000</pubDate>
		<dc:creator>bo</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://dev.bostone.us/?p=238</guid>
		<description><![CDATA[How to write static utility methods that can be tested (or mocked) using JUnit framework]]></description>
			<content:encoded><![CDATA[<p>I like to use static utilities to write parsing routines and other utility methods where code relies only on passed parameters and returns some type of immutable object such as String. However there&#8217;s one caveat &#8211; I also like to write JUnit tests for all these routines and here I&#8217;m seemingly out of luck. So I developed the following (singleton-based) pattern in implementing my static utilities. Let say I have MyUtils class and inside I want to have all API methods declared as &#8220;public static&#8221;.</p>
<ol>
<li>Define <code>private static final MyUtils </code> filed</li>
<li>Place your utility method code inside a &#8220;regular&#8221; protected method</li>
<li>Make your public static utility method refer to the internal MyUtils static instance</li>
</ol>
<p>In code it will look like this</p>
<pre type="code" class="java">
public class MyUtils {
    private static final MyUtils UTILS = new MyUtils();

    /**
     * Hide constructor from the outside of the package
     */
    MyUtils() {}

    public static String parseUpdates(String html) throws IOException, SAXException {
        return UTILS._parseUpdates(html);
    }

    String _parseUpdates(String html) throws IOException, SAXException {
        InputSource s = new InputSource(new StringReader(html));
        SaxParser parser = new SaxParser();
        MyUpdatesHandler handler = new MyUpdatesHandler();
        parser.setContentHandler(handler);
        parser.parse(s);
        return handler.getOutput();
    }
}
</pre>
<p>With this code now you can now write JUnit test as follows (test class shell and javadoc comments are omitted for briefness)</p>
<pre type="code" class="java">
    MyUtils utils;
    String html;
    @Before
    public void setUp() throws Exception {
        utils = new MyUtils();
        html = "&lt;div>Hello World&lt;/div>";
    }

    @Test
    public void testParseUpdates() throws Exception {
        String out = utils._parseUpdates(html);
        assertNotNull(out);
        // any other assertions that make sense
    }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dev.bostone.us/2009/08/17/writing-junit-friendly-static-code/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Android development &#8211; what not to do</title>
		<link>http://dev.bostone.us/2009/08/14/android-development-what-not-to-do/</link>
		<comments>http://dev.bostone.us/2009/08/14/android-development-what-not-to-do/#comments</comments>
		<pubDate>Fri, 14 Aug 2009 05:21:49 +0000</pubDate>
		<dc:creator>bo</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://dev.bostone.us/?p=231</guid>
		<description><![CDATA[Writing DroidIn was a very good exercise (it still is) Along the way, thanks to unforgiving users I&#8217;ve learn few things that Android developer should avoid at all cost. Here are few as well as tips:

Never ever execute things of any considerable length on the same (usually main) thread as your current Activity. Your users [...]]]></description>
			<content:encoded><![CDATA[<p>Writing DroidIn was a very good exercise (it still is) Along the way, thanks to unforgiving users I&#8217;ve learn few things that Android developer should avoid at all cost. Here are few as well as tips:</p>
<ul>
<li>Never ever execute things of any considerable length on the same (usually main) thread as your current Activity. Your users will be presented with &#8220;Wait or Cancel&#8221; choice and
<ol>
<li>They will be annoyed</li>
<li>90% will click &#8220;Cancel&#8221; and never use your app ever again</li>
</ol>
</li>
<li>What to do instead? Spawn the thread, use TimerTask or just plain Runnable and read some good Java concurrency book before you do that</li>
<li>Learn Services. That&#8217;s where the platform truly shines</li>
<li>Do not add new features before you make your existing one work as intended. And that means: Fix Bugs!</li>
<li>Yes, yes, I know &#8211; it&#8217;s boring and you have all these grande ideas, but if you don&#8217;t cover your basics well you will loose your users</li>
<li>Read your feedback. Even from trolls. It will make you angry so put that adrenalin into bug fixing.</li>
<li>Learn by example. Find good open source project and just see how it&#8217;s layout, how it&#8217;s designed and implemented. I&#8217;ve learn so much from <a href="http://code.google.com/p/oauth-signpost/">Oauth-Signpost</a>: thank you guys, you are an awesome bunch</li>
<li>Steal. Yeah &#8211; from forums, blogs and Open Source, just try to find something you can use or reuse and use/reuse it!</li>
<li>Ask questions, lots of questions! Android Developer forums are indispensable and so is http://stackoverflow.com</li>
<li>Keep coding, you will get it&#8230;</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://dev.bostone.us/2009/08/14/android-development-what-not-to-do/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GWT + GXT (extGWT) + Maven made possible</title>
		<link>http://dev.bostone.us/2009/08/05/gwt-gxt-extgwt-maven-made-possible/</link>
		<comments>http://dev.bostone.us/2009/08/05/gwt-gxt-extgwt-maven-made-possible/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 22:09:21 +0000</pubDate>
		<dc:creator>bo</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Web stuff]]></category>

		<guid isPermaLink="false">http://dev.bostone.us/?p=227</guid>
		<description><![CDATA[I just published GWT/GXT/Maven tutorial at extJs Wiki. It outlines step by step how to create and setup Eclipse project that unifies GWT, extGWT (GXT) and Maven
]]></description>
			<content:encoded><![CDATA[<p>I just published <a href="http://www.yui-ext.com/learn/Tutorial:GWT_GXT_and_Maven_howto">GWT/GXT/Maven tutorial</a> at extJs Wiki. It outlines step by step how to create and setup Eclipse project that unifies GWT, extGWT (GXT) and Maven</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.bostone.us/2009/08/05/gwt-gxt-extgwt-maven-made-possible/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Android: image only Spinner</title>
		<link>http://dev.bostone.us/2009/08/05/android-image-only-spinner/</link>
		<comments>http://dev.bostone.us/2009/08/05/android-image-only-spinner/#comments</comments>
		<pubDate>Tue, 04 Aug 2009 20:46:27 +0000</pubDate>
		<dc:creator>bo</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://dev.bostone.us/?p=224</guid>
		<description><![CDATA[Android uses a Spinner control to handle drop-down selection. For DroidIn app I wanted Spinner that looks like a regular button but when clicked behaves as a regular Spinner (pops up selection list, etc.).
To turn the Spinner into image button is easy &#8211; in XML definition simply add android:background="@drawable/select" where &#8220;select&#8221; refers to res/drawable/select.png
However you [...]]]></description>
			<content:encoded><![CDATA[<p>Android uses a Spinner control to handle drop-down selection. For DroidIn app I wanted Spinner that looks like a regular button but when clicked behaves as a regular Spinner (pops up selection list, etc.).</p>
<p>To turn the Spinner into image button is easy &#8211; in XML definition simply add <code>android:background="@drawable/select"</code> where &#8220;select&#8221; refers to res/drawable/select.png<br />
However you will now have a problem with the text of selected item overlaying Spinner&#8217;s background image. To solve this problem you will have to do some Java coding as follows:</p>
<pre name="code" class="java">
Spinner spin = (Spinner) d.findViewById(R.id.searchCriteria);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
  public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
    // hide selection text
    ((TextView)view).setText(null);
    // if you want you can change background here
  }
  public void onNothingSelected(AdapterView<?> parent) {}

});
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dev.bostone.us/2009/08/05/android-image-only-spinner/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Terminating Android Activity</title>
		<link>http://dev.bostone.us/2009/07/31/terminating-android-activity/</link>
		<comments>http://dev.bostone.us/2009/07/31/terminating-android-activity/#comments</comments>
		<pubDate>Fri, 31 Jul 2009 06:32:43 +0000</pubDate>
		<dc:creator>bo</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://dev.bostone.us/?p=222</guid>
		<description><![CDATA[I got a great tip from Mark Murphy @commonsguy on how to terminate Android app.
First &#8211; why do you need such awful thing? Here&#8217;s one scenario that I run into while trying to reproduce a bug reported by user

Activity calls another application
Original application terminates (basically I&#8217;m trying to simulate a very busy phone)
2nd app calls [...]]]></description>
			<content:encoded><![CDATA[<p>I got a great tip from Mark Murphy <a href="http://twitter.com/commonsguy">@commonsguy</a> on how to terminate Android app.<br />
First &#8211; why do you need such awful thing? Here&#8217;s one scenario that I run into while trying to reproduce a bug reported by user</p>
<ol>
<li>Activity calls another application</li>
<li>Original application terminates (basically I&#8217;m trying to simulate a very busy phone)</li>
<li>2nd app calls the original app</li>
<li>Original app restarts from scratch and processes callback</li>
</ol>
<p>So, how you do it? Very simple &#8211; just call
<pre>System.exit(0)</pre>
<p> I&#8217;m going to run some tests but my hunch is the app just drops dead, so don&#8217;t expect gracious Activity#onStop or even Activity#onDestroy. Or at least that&#8217;s what I think, but for my purpose it&#8217;s all right</p>
]]></content:encoded>
			<wfw:commentRss>http://dev.bostone.us/2009/07/31/terminating-android-activity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Name jdbc is not bound in this Context</title>
		<link>http://dev.bostone.us/2009/07/09/name-jdbc-is-not-bound-in-this-context/</link>
		<comments>http://dev.bostone.us/2009/07/09/name-jdbc-is-not-bound-in-this-context/#comments</comments>
		<pubDate>Wed, 08 Jul 2009 19:58:26 +0000</pubDate>
		<dc:creator>bostone</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Web stuff]]></category>

		<guid isPermaLink="false">http://dev.bostone.us/?p=189</guid>
		<description><![CDATA[If you ever get this error that most likely means that you defined your data source in context.xml but forgot to add resource reference to the web.xml. Easy fix &#8211; just add the following to web.xml

	
		My Datasource
		jdbc/myds
		javax.sql.DataSource
		Container
	

]]></description>
			<content:encoded><![CDATA[<p>If you ever get this error that most likely means that you defined your data source in context.xml but forgot to add resource reference to the web.xml. Easy fix &#8211; just add the following to web.xml</p>
<pre name="code" class="xml">
	<resource-ref>
		<description>My Datasource</description>
		<res-ref-name>jdbc/myds</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
	</resource-ref>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://dev.bostone.us/2009/07/09/name-jdbc-is-not-bound-in-this-context/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Refactoring code</title>
		<link>http://dev.bostone.us/2009/06/20/refactoring/</link>
		<comments>http://dev.bostone.us/2009/06/20/refactoring/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 18:00:36 +0000</pubDate>
		<dc:creator>bostone</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Web stuff]]></category>

		<guid isPermaLink="false">http://dev.bostone.us/?p=172</guid>
		<description><![CDATA[These are random notes taken while refactoring code at work
Patterns, Anti-patterns, best and worth practices, etc.
Don&#8217;t try too hard with your names (anti-pattern)
When define name for your entities one should be concern with what the entity is rather than how it relates to the different entities. Good example would be a &#8220;TestRunResultResultTest&#8221; which gives not [...]]]></description>
			<content:encoded><![CDATA[<h3>These are random notes taken while refactoring code at work</h3>
<p>Patterns, Anti-patterns, best and worth practices, etc.</p>
<h5>Don&#8217;t try too hard with your names (anti-pattern)</h5>
<p>When define name for your entities one should be concern with what the entity is rather than how it relates to the different entities. Good example would be a &#8220;<strong>TestRunResultResultTest</strong>&#8221; which gives not a slightest hint that this is a POJO (plain old java object) that holds data produced by validation logic applied to the execution of the single shell script. Name like &#8220;<strong>ValidationResult</strong>&#8221; would describe this entity much better and don&#8217;t produce monsters such as <tt>testRunResultResultTestDao.getTestRunResultResultTestForTestRunResult</tt> (say it aloud 5 times)</p>
<h5>Don&#8217;t add features until asked by customer</h5>
<p>I&#8217;m referring to the validation above which seems to do the same job as test script only it is harder to configure. The following is email that I send out that explains my point of view</p>
<blockquote><p>AIMV back end that I&#8217;m refactoring now has a &#8220;Validation&#8221; part. In the back end code it&#8217;s not really implemented (the only validation there is some hardcoded regexpression applied to stderr output). From what I understand validation is supposed to validate the output produced by the script and should be driven by the database table that holds things like validation type, expected outcome, etc.</p></blockquote>
<blockquote><p>Since we can have multiple scripts attached to each test case I have a hard time distinguishing between the validation and having another script in the test case if the existing one(s) does not provide sufficient information. I think for the most cases just the outcome of the individual shell script (exit code) should be sufficient to indicate success of failure. If such script produces the output that needs to be parsed additionally it would be easier for the script writer to add another script and to pipe and parse the outcome. I propose to remove post-validation from the database and the code and instead rely on ability to add multiple scripts to the individual test case. To give user chance to determine &#8220;what went wrong&#8221; we will provide ability to look at the produced output (stdout and/or stderr) from the front end for each executed script</p></blockquote>
<h5>Unnecessary exposure to external code</h5>
<p>Yes, yes &#8211; we do use Spring and probably always will. However that doesn&#8217;t mean we have to put direct references to the framework classes into our code. Good example is our DAO interfaces where each method throws <tt>org.springframework.dao.DataAccessException</tt>. There&#8217;s actually another reason why it&#8217;s wrong: best practice calls for you defining your own exceptions by extending common Java API exceptions. So in the case of DAO method the appropriate way of declaring the DAO exception would be extending <tt>java.lang.RuntimeException</tt> and choosing appropriate name (like AimvDataAccessException). By doing this our interfaces will stay framework neutral which they should as much as possible</p>
<h5>Non-functional screen elements</h5>
<p>If you have screen elements that are not functional &#8211; it&#8217;s probably a good idea to remove or hide these unless you are actively working on it</p>
<h5>Never nest your loops</h5>
<p>If you have one FOR or WHILE loop nested inside another one it&#8217;s time to refactor the internal loop into it&#8217;s own method. It dramatically improves readability of the code and promotes the reuse (how many times did you cut/paste your loop today?)</p>
<h5>Replace complex logic inside the IF test (not body) with a method</h5>
<p>So if you have logic inside your IF parenthesis spilling to the second line its time to grab that code and put in into a local variable or even better &#8211; refactor it to a method that returns a boolean. It&#8217;s very simple if you are using Eclipse. Just highlight the code and do <tt>right-click-&gt;Refactor-&gt;Exctract Method</tt>. So</p>
<div class="code panel" style="border-width: 1px;">
<div class="codeContent panelContent">
<pre class="java">if (dis == that &amp;&amp; (that != this.somethingElse || foo.equals(this.boo)) {
    // do something
}</pre>
</div>
</div>
<p>becomes</p>
<div class="code panel" style="border-width: 1px;">
<div class="codeContent panelContent">
<pre class="java">if (isThisSane(dis, that, foo)) {
    // do something
}</pre>
</div>
</div>
<h5>Copy/Paste as a root of all evil</h5>
<p>If you finding yourself copying and pasting parts of your code most likely you are committing a sin-of-sins. Actually there are tools that written just for the purpose of identifying this anti-pattern. Try <a rel="nofollow" href="http://pmd.sourceforge.net/">PMD plugin</a> on your code and you will be very surprised of results. And why not to do it? Copy/paste promotes code duplication which leads to linear, procedural, spaghetti-like and hard to maintain code. Before you copy/paste see if you can extract reusable method or even class and then it&#8217;s perfectly fine to reuse that.</p>
<h5>Why coding standards are important?</h5>
<p>If the standards were followed then we wouldn&#8217;t have Script_Packages.java and ScriptPackage.java in the same folder.</p>
<h5>Don&#8217;t make your models too special</h5>
<p>Models ahould be POJOs with no 3rd party dependencies. For example, we have Script domain object that extends Package. That one in turn implements JSONSerializable interface. As result &#8211; backend application has to include json.jar as one of dependencies</p>
<h5>DO NOT (Sorry I&#8217;m yelling) use System.out.println</h5>
<p>Why? I&#8217;ll give you 3 reasons</p>
<ul>
<li>You are not using debugger, which means you are operating at 20% of your potential productivity</li>
<li>You are not using logging facilities (Java logging or Log4j) which in a turn means that you are polluting your code left and right and the only choice you have is to remove sysouts manually or leave these in code which will slow your code down</li>
<li>It&#8217;s not cool<br />
Generally sysouts should not be substitutes for tool-based debugging, and you should have carefully though through logging statements in strategic places that should be permanent part of your code. Verbosity of your log should not be regulated by cut and paste but rather by setting debug level in configuration file</li>
</ul>
<h5>Do not swallow your exception</h5>
<p>The exception handling will be eventually put in the separate article but most importantly follow these simple rules:</p>
<ul>
<li>Rethrow (or wrap into RuntimeException) your exceptions and let them &#8220;bubble up&#8221;</li>
<li>If catching and rethrowing (wrapping) do not forget to pass original exception as an argument (or you will loose stacktrace and messages)</li>
<li>When you finally deal with the exception, inside your CATCH block use <tt>LOG.error(Exception)</tt> or at very least <tt>e.printStackTrace()</tt>. If you don&#8217;t, your log will never reflect the valuable information</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://dev.bostone.us/2009/06/20/refactoring/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

