<?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>Turnleaf Design &#187; Tutorial</title>
	<atom:link href="http://www.turnleafdesign.com/category/tutorial/feed" rel="self" type="application/rss+xml" />
	<link>http://www.turnleafdesign.com</link>
	<description>Ramblings of a junior developer</description>
	<lastBuildDate>Wed, 11 Nov 2009 05:56:28 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Mocking JDBC Connections with MockRunner</title>
		<link>http://www.turnleafdesign.com/mocking-jdbc-connections-with-mockrunner</link>
		<comments>http://www.turnleafdesign.com/mocking-jdbc-connections-with-mockrunner#comments</comments>
		<pubDate>Wed, 11 Nov 2009 05:54:11 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Mock]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=285</guid>
		<description><![CDATA[Last week I published an article, An Intro into Test Driven Development with Junit4, which got somewhat mixed reviews. One particular commenter on reddit suggested I didn't understand that unit tests shouldn't talk to its data source. I decided to do some investigating into his claims, you can check out my findings here. I was [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fmocking-jdbc-connections-with-mockrunner"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fmocking-jdbc-connections-with-mockrunner" height="61" width="51" /></a></div><p>Last week I published an article, <a href="  http://www.turnleafdesign.com/an-intro-into-test-driven-development-with-junit4" target="_blank">An Intro into Test Driven Development with Junit4</a>, which got somewhat mixed reviews. One particular commenter on reddit suggested I didn't understand that unit tests <a href="http://www.reddit.com/r/programming/comments/9yq8p/an_intro_into_test_driven_development_with_junit4/c0f29uc" target="_blank">shouldn't talk to its data source</a>. I decided to do some investigating into his claims, you can check out my findings <a href="http://www.turnleafdesign.com/ramblings-should-unit-tests-talk-to-a-data-source" target="_blank">here</a>. I was however intrigued none the less and started looking for a tool that would allow me to easily mock a JDBC connection. I found <a href="http://mockrunner.sourceforge.net/" target="_blank">Mockrunner</a> to be the easiest to use of the ones I have found. Below is a brief tutorial on how to use Mockrunner. (Keep in mind that I am still fairly new to using Mockrunner)<span id="more-285"></span></p>
<p>In the class I am testing I am explicitly calling the columns I am retrieving by name. So I need to add these column names to my mock ResultSet.</p>
<pre class="java" name="code" style="display: none;">
result.addColumn("Date");
result.addColumn("High");
result.addColumn("Low");
result.addColumn("Condition");
result.addColumn("ID");</pre>
<p>Obviously I also retrieve data from a result set so I must also insert data into the mock ResultSet. There are several ways to do this, but the easiest I found was using a list. You must add elements to the list in the same order as you added columns to the ResultSet.</p>
<pre class="java" name="code" style="display: none;">
List&lt;Object&gt; rowItems = new ArrayList&lt;Object&gt;();
rowItems.add(new Date(0));
rowItems.add(72);
rowItems.add(56);
rowItems.add("Cloudy");
rowItems.add(1);</pre>
<p>In my actual test case I can verify that I am actually gathering the contents of the result set correctly and that the correct SQL statement was run.</p>
<pre class="java" name="code" style="display: none;">
prepareRS();
ForecastDAO dao = new ForecastDaoImpl(getConnection());
List&lt;Forecast&gt; forecasts = dao.getAllForecasts();

assertTrue(!forecasts.isEmpty());
verifySQLStatementExecuted("SELECT * FROM forecast");
assertEquals(73, forecasts.get(1).getHigh());</pre>
<p>This is but scratching the surface of MockRunner's potential and using mocks at large. I hope this brief tutorial was helpful in getting you started using MockRunner. You can checkout the entire test class <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/22/trunk/%20forecastaccuracychecker/forecastchecker/test/com/tld/dao/TestForecastDaoImpl.java" target="_blank">here</a> and the class that I am testing <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/20/trunk/%20forecastaccuracychecker/forecastchecker/src/com/tld/dao/ForecastDaoImpl.java" target="_blank">here</a>. If you want to get an entire working version of the project be sure to read the <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/20/trunk/%20forecastaccuracychecker/forecastchecker/src/com/tld/dao/ForecastDaoImpl.java" target="_blank">technical guide</a>. Let me know if you have any questions or want to add your own comments.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x60, created 9/14/09 */
google_ad_slot = "1115297999";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Mock' rel='tag' target='_blank'>Mock</a>, <a class='technorati-link' href='http://technorati.com/tag/Programming' rel='tag' target='_blank'>Programming</a>, <a class='technorati-link' href='http://technorati.com/tag/Testing' rel='tag' target='_blank'>Testing</a>, <a class='technorati-link' href='http://technorati.com/tag/Unit+testing' rel='tag' target='_blank'>Unit testing</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/mocking-jdbc-connections-with-mockrunner/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Intro into Test Driven Development with JUnit4</title>
		<link>http://www.turnleafdesign.com/an-intro-into-test-driven-development-with-junit4</link>
		<comments>http://www.turnleafdesign.com/an-intro-into-test-driven-development-with-junit4#comments</comments>
		<pubDate>Tue, 27 Oct 2009 04:26:16 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Unit]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=260</guid>
		<description><![CDATA[Please read the technical guide before starting this tutorial.
This article will mark the first of a long-term series covering professional software development. For the lowdown on this project check out this article. Be sure to give me your feedback as it will be vital in helping me develop better tutorials in the future.
Test driven development [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fan-intro-into-test-driven-development-with-junit4"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fan-intro-into-test-driven-development-with-junit4" height="61" width="51" /></a></div><p>Please read the <a href="http://www.turnleafdesign.com/?page_id=263" target="_blank">technical guide </a>before starting this tutorial.</p>
<p>This article will mark the first of a long-term series covering professional software development. For the lowdown on this project check out <a href="http://www.turnleafdesign.com/?p=266" target="_blank">this article</a>. Be sure to give me your feedback as it will be vital in helping me develop better tutorials in the future.</p>
<p>Test driven development seemed like a natural choice as a lead off to my series of tutorials as I had to explain why I am writing all these tests. It is also a very good development methodology that will actually save a lot of time by reducing the amount of time spent debugging. For this tutorial and the entire project, I will be using Junit4. For a synopsis on test driven development you can check out the wikipedia article <a href="http://en.wikipedia.org/wiki/Test-driven_development" target="_blank">here</a>. If you need a brief refresher on JUnit you can read my tutorial <a href="http://www.turnleafdesign.com/?p=145" target="_blank">here</a> (written in Junit3).<br />
<span id="more-260"></span><br />
The goal of this tutorial, from a project stand point, is to get the connection to our (MySQL) database working. To do this we are going to need several things: a MySQL server, a client to access the server, and a JDBC driver to allow our application to access the server.</p>
<p>The MySQL server:<br />
I will be using MySQL server 5.0 for this project, you can download it <a href="http://dev.mysql.com/downloads/mysql/5.0.html#downloads" target="_blank">here</a>. The tutorial instructions will be based upon the user being “root,” the password “turnleaf,” and the url “http://localhost:3306.”</p>
<p>The MySQL client:<br />
I will be using <a href="http://www.heidisql.com/download.php" target="_blank">HeidiSQL</a> to query and manipulate the database. Once the client is installed import this sql file to setup the database and table.</p>
<p>The JDBC Driver:<br />
You can download the JDBC driver <a href="http://dev.mysql.com/downloads/connector/j/5.0.html" target="_blank">here</a>. Please include it on your projects build path.</p>
<p>To begin this project, please checkout revision 7 from the code repository.</p>
<p>Once you have downloaded the project go ahead and navigate around it a little bit. You will notice I already have several source files; Forecast, ForecastDao, and ForecastDaoImpl. Forecast is a bean for holding all weather information for a specific date (this bean will likely be modified in the future). We also have ForecastDao which is an interface and ForecastDaoImpl which implements ForecastDao. I plan on covering interfaces in more detail in the future, but if you are unfamiliar with the concept you can read a brief description <a href="http://java.sun.com/docs/books/tutorial/java/concepts/interface.html" target="_blank">here</a>.</p>
<p>Update to revision 8 and you will see I added in my first unit test. The unit test is checking to see if I get any returns when I run getAllForecasts(). Here is the code:</p>
<pre name="code" class="java">
@Test

public void testGetAllForecasts(){

List&lt;Forecast&gt; forecasts = dao.getAllForecasts();

Assert.assertTrue(!forecasts.isEmpty());

}
</pre>
<p>If you attempt to run the test you should get a null point error when you attempt to check if forecasts is empty. If you look at the implementation of getAllForecasts() in ForecastDaoImpl it is obvious why, getAllForecasts() is returning null. This is one of the tenants of TDD, write fail first tests.</p>
<p>Go ahead and update to <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/9/trunk/%20forecastaccuracychecker/forecastchecker/src/com/tld/dao/ForecastDaoImpl.java" target="_blank">revision 9</a>. You will see I have added connection information to getAllForecasts(). Don't worry about it being messy we will refactor it later. Go ahead and run the unit test again. You will still fail, but in the console shows we are successfully connecting to the database.</p>
<p>Update to <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/10/trunk/%20forecastaccuracychecker/forecastchecker/src/com/tld/dao/ForecastDaoImpl.java" target="_blank">revision 10</a>. I have made several more changes, most noticeably if you run the test it should now pass! (If not check to make sure your database is setup correctly) Before we start celebrating too much, lets actually check the contents of the list to make sure we are getting the right data. Update to <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/11/trunk/%20forecastaccuracychecker/forecastchecker/src/com/tld/dao/ForecastDaoImpl.java" target="_blank">revision 11</a>, I have added a few more checks, and we are in fact getting the correct data, awesome!</p>
<p><strong>Author note:</strong> For some dumb reason when you create a new Junit4 test class in Eclipse it does not automatically inherit TestClass. Anyways I inherit that class now so you can just do assertEquals(expected, actual) instead of Assert.assertEquals(expected, actual).<br />
If you checked the implementation of getAllForecasts() before updating to revision 10, you will noticed I am only setting the date value of my forecast bean. My new tests initially failed (I originally thought I was setting all fields), thus the importance of not only writing unit tests, but writing good unit tests.</p>
<p>So now it is time to start refactoring. With our unit test we now have a good baseline of how the system should behave. This way when we are making changes we can be confident we are not breaking the system because we will be getting the same output for the same input.</p>
<p>Update to <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/13/trunk/%20forecastaccuracychecker/forecastchecker/src/com/tld/dao/ForecastDaoImpl.java" target="_blank">revision 13</a>. You will see that I have created the getConnection() method and that contains the database connection logic.</p>
<pre name="code" class="java">
private Connection getConnection() {

Connection conn;

try {

String userName = "root";

String password = "turnleaf";

String url = "jdbc:mysql://localhost/weather";

Class.forName("com.mysql.jdbc.Driver").newInstance();

conn = (Connection) DriverManager.getConnection(url, userName,

password);

} catch (Exception e) {

throw new DataAccessException(e);

}

return conn;

}
</pre>
<p>I pretty much just copied and pasted (one of the VERY few times copying and pasting is ok) the connection logic into this method. The most noticeable change I made is in the catch clause. There is a bunch of different exceptions that could be thrown when attempting to connect to the database, sine they all end in the same scenario, unable to connect to the database, I kept the same generic catch(Exception). However you should never just throw exception so I created my own custom exception called DataAccessException. Inside the super(Throwable) constructor I set it up to add a message stating “Unable to connect to data source,” I also have it extend RunTimeException turning it into an <a href="http://java.sun.com/docs/books/tutorial/essential/exceptions/runtime.html" target="_blank">unchecked exception</a>.</p>
<p><strong>***Philosophical warning***</strong><br />
This is philosophical decision. As projects become more complex it can become difficult to catch and/or throw an exception at every level. However, you should catch the exception at some point to give the user a reasonable error message and let you know when the application is throwing exceptions. There is another school of thought that all exceptions should be checked as it lets a developer know what exceptions and method could throw, and other various reasons.</p>
<p>Between the message and the name of the exception, it should be pretty clear that when this exception is thrown it means the application failed to connect to the database. Running the unit test we will see everything is still passing so we can be confidant that the refactoring did not break the system.</p>
<p>Update to <a href="http://forecastaccuracychecker.googlecode.com/svn/!svn/bc/14/trunk/%20forecastaccuracychecker/forecastchecker/src/com/tld/dao/ForecastDaoImpl.java" target="_blank">revision 14</a> and you will see I refactored out the closing of the connection. Exceptions should never be ignored, personally I would say being unable to close a database connection could be a major issue. So instead of catching Exception I changed it to only catch SQLException and throw the DataAccessException except I will have my own message in their stating the connection could not be closed. Here is what the closeConnection() method looks like:</p>
<pre name="code" class="java">
private void closeConnection(Connection conn) {

if (conn != null) {

try {

conn.close();

} catch (SQLException e) {

throw new DataAccessException("Could not close connection", e);

}

}

}
</pre>
<p>From what it originally looked like, the getAllForecast() method is starting to look a lot better as well as the ForecastDaoImpl class in general. Adding new methods that retrieve data from the database will be easier as all I have to do to get a connection is call getConnection() and to close it closeConnection(Connection). On top of that if I need to change my database connection information I only have to do it in one area.</p>
<p>Despite this refactoring, this is hardly an ideal data access layer. With the test unit already created go ahead and continue to refactor getAllForecast(), a good place to start would be how I create a new Forecast object. I would also suggest adding some new functionality yourself a couple of examples might be; getForecastByDate(Date) or getForecastByCondition(String condition) (Remember create unit tests!). I will continue to refactor and update this work myself. So you can run updates and compare your work to my own.</p>
<p>Addendum and thanks:<br />
Because I am an idiot I couldn't remember how to write a JDBC connection. My initial connection method is predominantly based off of the code in this article: <a href="http://www.kitebird.com/articles/jdbc.html" target="_blank">http://www.kitebird.com/articles/jdbc.html</a><br />
For being able to go to a specific revision with a url:<br />
<a href="http://www.perhammer.com/2008/07/subversion-in-url-revision-browsing.html" target="_blank">http://www.perhammer.com/2008/07/subversion-in-url-revision-browsing.html</a><br />
<script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x15, created 9/22/09 */
google_ad_slot = "6237316105";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Best+practices' rel='tag' target='_blank'>Best practices</a>, <a class='technorati-link' href='http://technorati.com/tag/Java' rel='tag' target='_blank'>Java</a>, <a class='technorati-link' href='http://technorati.com/tag/Programming' rel='tag' target='_blank'>Programming</a>, <a class='technorati-link' href='http://technorati.com/tag/Unit' rel='tag' target='_blank'>Unit</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/an-intro-into-test-driven-development-with-junit4/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Taming of the Subversion, a SVN primer; part 3</title>
		<link>http://www.turnleafdesign.com/taming-of-the-subversion-a-svn-primer-part-3</link>
		<comments>http://www.turnleafdesign.com/taming-of-the-subversion-a-svn-primer-part-3#comments</comments>
		<pubDate>Sun, 18 Oct 2009 23:18:44 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Promised Land]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[SVN]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=237</guid>
		<description><![CDATA[In the third and final part to my SVN primer I will finish up with my day to day tasks and I will go over how to add SVN properties to your project. The first two parts can be found here: 1,  2.

More Terminology:
BASE – Refers to the most recent revision currently on your local [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Ftaming-of-the-subversion-a-svn-primer-part-3"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Ftaming-of-the-subversion-a-svn-primer-part-3" height="61" width="51" /></a></div><p>In the third and final part to my SVN primer I will finish up with my day to day tasks and I will go over how to add SVN properties to your project. The first two parts can be found here: <a href="http://www.turnleafdesign.com/?p=206" target="_blank">1</a>,  <a href="http://www.turnleafdesign.com/?p=230" target="_blank">2</a>.<br />
<span id="more-237"></span></p>
<h3>More Terminology:</h3>
<p><strong>BASE</strong> – Refers to the most recent revision currently on your local workspace.</p>
<h3>SVN Commands:</h3>
<p><strong>Comparing revisions </strong>– To see what changes have been made between two revisions a comparison can be run. The changes will be highlighted in gray, along with a box showing where in the older revision the change fits in. To compare revisions right click&gt;compare with and then select the option that best suits your needs.</p>
<p><strong>Merging</strong> – One of my least favorite of SVN commands, not because there is anything wrong with the merge feature (it's actually a great feature), but often when I run merges I have to deal with several conflicts, which I never find an enjoyable experience.  Anyways merging is a little trickier than you might think. Initially you might try merging the head of your branch (or whatever you are merging) with the head of your trunk, however this is incorrect. You actually need to merge the head of your branch with the revision of your trunk when you made the branch. This needs to be done because Subversion needs to know what actually has changed since the branch was made.</p>
<p><strong>Add</strong> – If there is a file that is not under version control, but you would like it to be include this can be done by right clicking on the file team&gt;add to version control</p>
<p><strong>Ignore</strong> – On the flip side, if  you do not want a file to be under version control right clicking&gt;team&gt;add to svn:ignore</p>
<p><strong>SVN properties</strong> – One really useful feature is svn properties. There are a wide assortment of svn properties that allow you to do things like add meta information to a file (author, revision number, last modified, etc.), include a tracking number and link to a bug tracking system, among many other options. The easiest way to setup properties using subclipse is through the “Show Properties” view. Right click on the SVNProject root folder and go to Team&gt;Show Properties. To add a property right click any where in the spreadsheet looking area and select “add property.” Select the desired property and setup the property's value. To setup the ability to use a bug tracking through svn we will need the following three properties added:</p>
<p style="text-align: center;"><img class="aligncenter" src="http://www.turnleafdesign.com/images/SVNProperties.png" alt="null" /></p>
<p><strong>Bugtraq:label</strong> - Displays a message next to the box where a developer would put the (comma separated) issue numbers.<br />
<strong>Bugtraq:url</strong> – This is the url to your bug tracking system. The “%BUGID%” appends the tracking numbered entered to its location in the url.<br />
B<strong>ugtraq:message</strong> - Displays a message in the history view. “%BUGID%” creates a link to the bug entered during the commit.</p>
<p>The end product, when you select a specific revision in the view history view in the bottom left you should get a message like “Tracker #s: 123” With "123" being a link tracker 123 in your bug tracking system. Eclipse has a built in browser, so when this link is clicked a browser window should open within Eclipse taking you to the issue.</p>
<p>This concludes my SVN primer. I hope anybody who reads this finds it useful. If you have any questions let me know. For more information on SVN you can check out these links:<br />
<a href="http://markphip.blogspot.com/ " target="_blank">http://markphip.blogspot.com/ </a>- The blog run by the director of subversion engineering at Collbanet<br />
<a href="http://svnbook.red-bean.com/en/1.5/index.html " target="_blank">http://svnbook.red-bean.com/en/1.5/index.html </a>– A huge guide on how to use Subversion<script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x15, created 9/22/09 */
google_ad_slot = "6237316105";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Subversion' rel='tag' target='_blank'>Subversion</a>, <a class='technorati-link' href='http://technorati.com/tag/SVN' rel='tag' target='_blank'>SVN</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/taming-of-the-subversion-a-svn-primer-part-3/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Taming of the Subversion, a SVN primer; part 2</title>
		<link>http://www.turnleafdesign.com/taming-of-the-subversion-a-svn-primer-part-2</link>
		<comments>http://www.turnleafdesign.com/taming-of-the-subversion-a-svn-primer-part-2#comments</comments>
		<pubDate>Thu, 15 Oct 2009 04:29:34 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Promised Land]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[SVN]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=230</guid>
		<description><![CDATA[In part one I went over how to get SVN setup and configured on your system. In Part two I will get into  the day to day activities of using SVN. In this part of my SVN primer I will cover; Checking out, committing, updating, synchronizing, branchings, and tagging. I will also go over [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Ftaming-of-the-subversion-a-svn-primer-part-2"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Ftaming-of-the-subversion-a-svn-primer-part-2" height="61" width="51" /></a></div><p><a href="http://www.turnleafdesign.com/?p=206" target="_blank">In part one</a> I went over how to get SVN setup and configured on your system. In Part two I will get into  the day to day activities of using SVN. In this part of my SVN primer I will cover; Checking out, committing, updating, synchronizing, branchings, and tagging. I will also go over some terminology to help make things a little more clear. I will be using subclipse as my SVN client in this part of the primer. I find using SVN from within an IDE to be more natural and including directions for both subclipse and tortoiseSVN to be confusing and there is very little difference between the two anyways.<span id="more-230"></span></p>
<h3>Terminology:</h3>
<p><strong>Head Revision</strong> – Refers to the most recent revision in the repository.</p>
<p><strong>Trunk </strong>– The main working directory of a project.</p>
<h3>SVN Commands:</h3>
<p><strong>Checking out</strong> – To retrieve a project from the repository open up the “SVN Repositories” view and navigate to the project you wish to check out. Following with the example from part one it would be SVNProject&gt;Trunk&gt;SVNProject click finish when the next screen pops up. I find this method to be the easiest and quickest way to checkout a project.</p>
<p><strong>Committing </strong>– When you have modified a file (or created a new file) you will need to “commit” it for the file to be included in version control. Subclipse keeps track of the files you have modified and when they are out of sync with the repository they display an icon next to that file stating so, subclipse shows a brown box with a white asterisk (new files are a question mark). To commit your file right click on the file(s) you wish to commit and go to team&gt;commit . You will be presented with a pop up box, you here you will put a message of why you are committing a file, ALWAYS put a message. Messages will server as a quick reference when looking over a files history (explained below).</p>
<p><strong>Updating</strong> – To get the latest file(s) from the repository you will need to run an update. To perform an update select the file/folder(s) you want to have updated and right click team&gt;update to HEAD.</p>
<p><strong>Conflicts</strong> – A conflict arises when you have a file that is out of sync with version control and you have edited line(s) of code that have been checked in since the last time you have run an update. Because SVN cannot itself determine which piece of code is correct, you must manually look at the code and determine which is correct. Here is an example of a conflict:<br />
<img src="http://turnleafdesign.com/images/Picture%204.png" alt="null" /><br />
1.This is the change you made<br />
2.This is the change that has been made in subversion since you last updated<br />
3.This is several versions of the file that is in conflict<br />
1.XXXX.java.mine is the file on your local machine<br />
2.XXXX.java.r(lowest number) is the most recent file you retrieved from the repository<br />
3.XXXX.java.r(highest number) is the newest file in the repository</p>
<p>In order to resolve a conflict you need to determine which change is correct. In this case I will keep my change, so I will delete the SVN markup (&lt;&lt;&lt; .mine, ====, etc.) the change I do not like. So my file will like this:<br />
<img src="http://turnleafdesign.com/images/Picture%205.png" alt="null" /></p>
<p>You will also notice a weird little symbol that looks like a X with a square over it, this is the “conflict” symbol. You cannot commit a file to the repository that is in conflict. <span style="text-decoration: line-through;">To remove the conflict you must delete the .java.mine, java.r(lowest number), etc. files. Once this is done you can commit your file to the repository.</span> To resolve the conflict right click on the file and select Mark as Resolved, then select the action you wish to take. The "conflicts have been resolved option" uses the current file in your code view, "my file" will use the ".mine" file, incoming file will use the .r(highest number), base will use the .r(lowest number) file. (Thanks Mark!)</p>
<p><strong>Branching</strong> – Most work on a SVN project is done in the “trunk” folder. There maybe times though when a change needs to be made to a project, but that change cannot affect the trunk, or a change need to be made, but it cannot affect code that will be going to production. In these scenarios a “branch” is crated. A branch is a copy of the current head revision of a file(s) that is placed in a separate folder (typically under “branches”). To create a branch right clicks on the file/folder you wish to branch and go to team&gt;branch/tag&gt;select your destination ({project name}/branches&gt;name the new branch</p>
<p><strong>Tagging</strong> – A tag is like a branch, however it represents snapshot of a project instead of a working directory. Typically a tag represents a project version or code that has been pushed to a production environment. When you attempt to commit a file to a tag a warning message is displayed stating a file is being committed to a tag. To create a tag team&gt;branch/tag&gt;select your destination ({project name}/tags&gt;name the new tag.</p>
<p><strong>REMINDER:</strong> When you branch or tag a project, the branch/tag is created off the Head revision of what is in the repository NOT what is stored locally on your computer.</p>
<p><strong>View history</strong> - Subclipse allows you the the view the history of a file(s) stored in the SVN repository. The history view will show when the file has been modified (checked into SVN), the revision number, and the comments when the file was committed. To view the history of a file right click on it go to team&gt;show history.</p>
<p><strong>Reverting </strong>– Reverting allows you to retrieve a previous version of a file from the repository. Reverting is typically done to get rid of unwanted changes or for debugging reasons (i.e. a bug is known to exist in version X of a project). A neat thing SVN allows you to do is revert an entire project to a specific revision. When this is done all files are not the same revision number, but the version number they where at the time that revision was made. To perform a revert right click&gt;team&gt;update to revision&gt;select the revision you wish to revert to.</p>
<p>This will conclude part two of the SVN primer. In part three I will go over a few more day to day task of using SVN. I will also go into a few advanced topics like setting up SVN properties which can be quite useful. Check back later this week for part three! If you have any questions please let me know.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x15, created 9/22/09 */
google_ad_slot = "6237316105";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Best+practices' rel='tag' target='_blank'>Best practices</a>, <a class='technorati-link' href='http://technorati.com/tag/Subversion' rel='tag' target='_blank'>Subversion</a>, <a class='technorati-link' href='http://technorati.com/tag/SVN' rel='tag' target='_blank'>SVN</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/taming-of-the-subversion-a-svn-primer-part-2/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Taming of the Subversion, a SVN primer; part 1</title>
		<link>http://www.turnleafdesign.com/taming-of-the-subversion-a-svn-primer-part-1</link>
		<comments>http://www.turnleafdesign.com/taming-of-the-subversion-a-svn-primer-part-1#comments</comments>
		<pubDate>Tue, 13 Oct 2009 03:34:30 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[SVN]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=206</guid>
		<description><![CDATA[In my first multi-part tutorial I will give an in-depth primer on how to use Subversion (SVN). Subversion is one of the mostly widely used version control systems in the software development industry. Subversion is based off of CVS and while I haven't personally used CVS I'd imagine the vast majority of what is in [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Ftaming-of-the-subversion-a-svn-primer-part-1"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Ftaming-of-the-subversion-a-svn-primer-part-1" height="61" width="51" /></a></div><p>In my first multi-part tutorial I will give an in-depth primer on how to use Subversion (SVN). Subversion is one of the mostly widely used version control systems in the software development industry. Subversion is based off of CVS and while I haven't personally used CVS I'd imagine the vast majority of what is in this primer can be transferred over fairly easily to CVS. So this primer should effectively prepare you for any version control system you will likely encounter. There are a couple other version control systems out there, but these are the two major players.<span id="more-206"></span></p>
<p>The primer will be broken down into three parts; part one will focus on setting up a SVN server, installing the SVN clients and creating a new project. Part two will go over most of the day to day functions of using SVN. In part three I will go over a few more day to day SVN functions as well as go into a few advanced subjects like setting up properties, which can be very useful. This primer will be used as platform for some exciting future projects I will be doing on this site. If you do not yet know how to use SVN I would suggest reading up on this primer as it will be quite useful both for this site and your career.</p>
<h3>Setting up the server</h3>
<p>A natural starting point for this primer would be to get a SVN server setup on your system. While there are several options out there, the one I am most familiar with is <a href="http://www.visualsvn.com/server/download/" target="_blank">VisualSVN</a>. Click on the link and download VisualSVN. Once the file has finished downloading follow these steps:<br />
1. Select install VisualSVN and management console<br />
2. Uncheck use secure connection, port can be set to whatever you want, but I will be using the default in my primer (443), same goes for the repository location.<br />
3. Install</p>
<p>Once the installation is complete the management console should automatically start. We now need to configure the SVN server:<br />
1. Select create a new repository<br />
2. Give your repository a name, I gave mine SVNTest, leave “Create default structure” unchecked<br />
3. Next create a new user, my user name is ninjaneer with the username as the password.<br />
4. On the left hand side of the screen, expand repositories, right click on SVNTest and create a new project called “SVNProject”</p>
<h3>The clients</h3>
<p>In order to effectively use SVN we will need to use a client. I will be actually covering two SVN clients; TortoiseSVN and Subclipse.</p>
<p>Go here to download <a href="http://tortoisesvn.net/downloads" target="_blank">TortiseSVN</a>. Choose either the 32-bit or 64-bit flavor. This is a very standard install, just accept all the defaults and hit install.</p>
<p>Installing Subclipse is a little different as it is an Eclipse plugin, but luckily Eclipse has a sweet plugin installer to handle most of this for us. (If you haven't used it before <a href="http://agile.csc.ncsu.edu/SEMaterials/tutorials/install_plugin/index_v35.html" target="_blank">here is a tutorial</a> on how to use Eclipse's built in plugin install feature.) Here is the download site  for subclipse: http://subclipse.tigris.org/update_1.6.x. Select “Core SVNKit Library” and “Subclipse” and continue with the plugin install.</p>
<h3>Adding a project to SVN</h3>
<p>In Eclipse we are going to create a new project. I will name the project “SVNProject” and I will accept the defaults. To upload a project to a SVN repository right click on the project folder&gt;Team&gt;Share Project&gt;SVN. You will need to enter the url of your SVN repository; open up the VisualSVN management console and look for “Server URL is: http://xxxxx:443/svn/.” Copy the url and paste it into the dialogue box in Eclipse. BEFORE YOU CLICK NEXT, type in the repository name, in this example it is SVNTest, so your repository url should look similar to this http://xxxxx:443/svn/SVNTest. On the next page select “use specified folder name” then click the select button, select SVNProject&gt;trunk. For organizational purposes it is best to give each project in the repository its own; trunk, branch, tag hierarchy, otherwise it can become very difficult to manage multiple projects.</p>
<p>This will conclude the first part of the SVN primer. In part two I will go over more of the day to day tasks of using SVN; checking out a project, committing, updating, resolving conflicts, synchronizing, branching, tagging, and reverting as well as some come terms. Check back later this week for part two. If you have any questions or comments please let me know.</p>
<h3>Update:</h3>
<p>Part two has been posted, <a href="http://www.turnleafdesign.com/?p=230" target="_blank">check it out</a></p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x60, created 9/14/09 */
google_ad_slot = "1115297999";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Subversion' rel='tag' target='_blank'>Subversion</a>, <a class='technorati-link' href='http://technorati.com/tag/SVN' rel='tag' target='_blank'>SVN</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/taming-of-the-subversion-a-svn-primer-part-1/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>6 Steps for fixing any bug</title>
		<link>http://www.turnleafdesign.com/6-steps-for-fixing-any-bug</link>
		<comments>http://www.turnleafdesign.com/6-steps-for-fixing-any-bug#comments</comments>
		<pubDate>Wed, 30 Sep 2009 23:42:19 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=144</guid>
		<description><![CDATA[Hate bugs? Yeah everybody does. Here are six steps that should resolve virtually every bug you encounter. 
1.Take responsibility – About 95% (a total guess) of the time if your application is not working as expected it is because you did something wrong. We all take pride in our code, but it pays in this [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2F6-steps-for-fixing-any-bug"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2F6-steps-for-fixing-any-bug" height="61" width="51" /></a></div><p>Hate bugs? Yeah everybody does. Here are six steps that should resolve virtually every bug you encounter. <span id="more-144"></span></p>
<p><strong>1.Take responsibility</strong> – About 95% (a total guess) of the time if your application is not working as expected it is because you did something wrong. We all take pride in our code, but it pays in this case to be humble. You will save yourself a lot of time and potentially face by first checking your code to see if there are any coding problems.</p>
<p><strong>2.Narrow down where the bug occurs</strong> – A natural step, if you want to be able to fix a bug you have to know where to start. Check the application log(s) to see if an exception is being thrown, use you intuition, or otherwise start at the highest reasonable level that would encapsulate the bug and start drilling down from there (e.g. if people can't login, then start with the login page).</p>
<p><strong>3.Write a unit test</strong> – Once you have an idea of where the problem might be write a unit test. Check to make sure you are getting the expected results out of your method calls. Keep writing unit tests until you get to the finest reasonable level of <a href="http://en.wikipedia.org/wiki/Granularity" target="_blank">granularity</a>. If you do not know how to write unit tests here is a <a href="http://www.turnleafdesign.com/?p=145" target="_blank">brief tutorial.</a></p>
<p><strong>4.Use the debugger </strong>– Depending upon the complexity of your system or unit test, you may want to step through your code line by line to; see what message are being sent, how the program is being executed (lines executed), and how the value of variables are being modified.</p>
<p><strong>5.Write to the logs</strong> – If you are still not able to resolve the problem, it doesn't show up in you unit test(s) (you may want to write better unit tests), or are unable to use units tests or a debugger (for example the bug is in a JSP) then include logging statements in your code and look for where things go awry.</p>
<p><strong>6.Seek help</strong> – If you still can't figure the problem out (or can't come up with a solution) seek help from your peers. Find someone who is either really good with programming or knows the application you are working on very well.</p>
<h3>Addendum</h3>
<p>So if you ran through all these steps and still can't figure out the problem you may not have screwed up. Double check your work and what you have done to make sure you have got everything covered. If everything looks good (or I guess bad) gather test data so the issue can be recreated and when you contact the person/vendor who you believe is responsible for the bug, give them the test data and explain as thoroughly as reasonable how to recreate the issue. If you don't do this then they may blow off your problem, because after all they have work too and don't have time to go searching for problems.</p>
<h3>One final note</h3>
<p style="text-align: left;">I wrote this article in contest to this <a href="http://sites.google.com/site/yacoset/Home/how-to-fix-bugs-step-by-step" target="_blank">article</a> which was recently posted on reddit . I disagree with the authors steps in resolving a bug. That is not to say the author is incorrect, just I disagree with him/her. I would suggest also reading that article (I agree with the “good practices”) and decide what is the best way to fix your bug(s). if you have any questions are steps you want to add let me know in the comments.</p>
<p style="text-align: left;">
<h3 style="text-align: left;">Update (10/2):</h3>
<p>It seems this article has become a conversation. Dustin Marx of <a href="http://marxsoftware.blogspot.com/" target="_blank">http://marxsoftware.blogspot.com/</a> has expanded upon this topic. I suggest giving his article a <a href="http://marxsoftware.blogspot.com/2009/10/common-debugging-steps-articulated.html">read</a>. His article contains information that is likely more relevant and useful for more experienced developers. Thanks Dustin!</p>
<p><script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x15, created 9/22/09 */
google_ad_slot = "6237316105";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Best+practices' rel='tag' target='_blank'>Best practices</a>, <a class='technorati-link' href='http://technorati.com/tag/Programming' rel='tag' target='_blank'>Programming</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/6-steps-for-fixing-any-bug/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>A brief intro into unit testing with JUnit</title>
		<link>http://www.turnleafdesign.com/a-brief-intro-into-unit-testing-with-junit</link>
		<comments>http://www.turnleafdesign.com/a-brief-intro-into-unit-testing-with-junit#comments</comments>
		<pubDate>Wed, 30 Sep 2009 23:42:10 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Noob Corner]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=145</guid>
		<description><![CDATA[Learning how to use the built-in IDE debuggers and write unit tests is as fundamental to being a developer as knowing how to write a for loop. These two tools will save you countless hours of frustration and help you write better code. Entire books are written on just these subjects, however today I will [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fa-brief-intro-into-unit-testing-with-junit"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fa-brief-intro-into-unit-testing-with-junit" height="61" width="51" /></a></div><p>Learning how to use the built-in IDE debuggers and write unit tests is as fundamental to being a developer as knowing how to write a for loop. These two tools will save you countless hours of frustration and help you write better code. Entire books are written on just these subjects, however today I will just give a simple tutorial on writing unit tests.<span id="more-145"></span> In this example I will be testing a <a href="http://www.turnleafdesign.com/?p=52" target="_blank">JavaBean</a> that could be used in a simple inventory system. You can download the project <a href="http://turnleafdesign.com/code_examples/UnitTestExample.zip" target="_blank">here</a>. If you need help setting up the project you can follow the instructions <a href="http://www.turnleafdesign.com/?page_id=142" target="_blank">here</a>.</p>
<blockquote><p>package com.dining;</p>
<p>public class Item {<br />
public String name;<br />
public int id;</p>
<p>public Item(String name, String id) throws IllegalArgumentException{<br />
if((name != null &amp;&amp; !name.equalsIgnoreCase("")) &amp;&amp; (id != null &amp;&amp; !id.equalsIgnoreCase("") &amp;&amp; id.matches("\\d*"))){<br />
this.name = name;<br />
this.id = Integer.parseInt(id);<br />
} else {<br />
throw new IllegalArgumentException("Invalid argument(s)");<br />
}<br />
}</p>
<p>public String getName() {<br />
return name;<br />
}</p>
<p>public void setName(String name) {<br />
this.name = name;<br />
}</p>
<p>public int getId() {<br />
return id;<br />
}</p>
<p>public void setId(int id) {<br />
this.id = id;<br />
}<br />
}</p></blockquote>
<p>For my unit test I want to make sure my two argument constructor is working as expected. That is, it will require me to give a valid name, a String object with at least one character, and a valid id, a number. If either of these arguments are incorrect I will throw an IllegalArgumentException.</p>
<p>First we need to create a unit test class to run unit tests. To do this I will create a JUnit class, in Eclipse you can right click in your package explorer view and in the pop menu scroll down to the “JUnit” option, be sure to do this under the “com.unittest” package in the “test” folder. I will be using JUnit 3 for this example. The convention for naming for unit test classes is “Test” followed by the name of the class you will be testing, so in this case “TestItem.” The defaults should be fine so go ahead and click ok.</p>
<p>Each unit test case is its own method. Again the convention with unit tests is to start the name with “test” followed by the method under test. This is can be a looser practice as you might want to name the unit test based upon the type of test your are running. In this case I will name the unit test “testItemValidArguments” because I will be only passing valid arguments into the constructor. Inside the unit test you will make a call to the method you are testing and you will run an assertion to check to make sure the right value is being returned. There are numerous assertion types:</p>
<p>assetEquals(expected, actual) which compares what you are expecting to what is actually returned<br />
assertTrue(condition) expects the passed condition to return true<br />
assertFalse(condition) expects the passed condition to return false</p>
<p>There are a couple of other ways of running tests but these are the major ones. When these methods return an unexpected value; unequal values, false when true expected and vice versa, this causes the test to fail. If you are running your test in Eclipse the JUnit view will display red. Conversely if the test passes the JUnit view will display Green.</p>
<p>So lets write our first unit test:</p>
<blockquote><p>public void testItemValidArguments() {<br />
Item item = new Item("Wrench", "1");<br />
assertEquals(2, item.getId());<br />
}</p></blockquote>
<p>No, I did not make a typo, go ahead and run the test an see what happens. Your test should fail (if it doesn't you have a problem). The JUnit view should look like this:<br />
<img src="http://turnleafdesign.com/code_examples/UnitTestImages/Picture%202.png" alt="" /></p>
<p>JUnit will let you know when you failed a test. In this case it's telling us that it was expecting “2” to be returned, but actually got “1.” Go ahead and change the expected value back to “1” and run the test again and it should pass. Ok so when we pass valid arguments the constructor works correctly. Now let's make sure the constructor lets us know when the arguments passed in are not valid. Let's write another units test:</p>
<blockquote><p>public void testIteamInvalidArguments() {<br />
Item item = new Item("Wrench", "A");<br />
assertEquals(“A”, item.getId());<br />
}</p></blockquote>
<p>Try running the test. Your JUnit view should look like this:<br />
<img src="http://turnleafdesign.com/code_examples/UnitTestImages/Picture%203.png" alt="" /><br />
Well good news bad news. The constructor validates the second field correctly, it is requiring a number, however we don't want our unit tests failing. All unit tests should “pass” when they run correctly so a change needs to be made. To cut to the chase this is one possible way of fixing the unit test:</p>
<blockquote><p>public void testIteamInvalidArguments() {<br />
try {<br />
Item item = new Item("Wrench", "A");<br />
fail("You should have thrown an exception!");<br />
} catch (IllegalArgumentException e) {<br />
//Do nothing<br />
}<br />
}</p></blockquote>
<p>As long as a fail is not returned within a JUnit test case the test passes, so in the test case if the IllegalArgumentException is thrown then we won't do anything because we are expecting that, however if the exception is not thrown then we want the test to fail. So on the line below where I create an Item object I call fail() and pass in a message, so if the exception is not thrown the test will fail and I will know I have a problem (and a message will be displayed in the JUnit view).</p>
<p>I will end my tutorial here. This should be enough to get your feet wet in unit testing. There are several other tests that could be written, for example checking to make sure name validation works. I plan on covering this subject in more depth so check back later. This is my first real tutorial, so please let me know if I glossed over anything. If you have any other questions please let me know.</p>
<p style="text-align: center;"><script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x15, created 9/22/09 */
google_ad_slot = "6237316105";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Best+practices' rel='tag' target='_blank'>Best practices</a>, <a class='technorati-link' href='http://technorati.com/tag/Programming' rel='tag' target='_blank'>Programming</a>, <a class='technorati-link' href='http://technorati.com/tag/Testing' rel='tag' target='_blank'>Testing</a>, <a class='technorati-link' href='http://technorati.com/tag/Unit+testing' rel='tag' target='_blank'>Unit testing</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/a-brief-intro-into-unit-testing-with-junit/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>If, else and nothing else</title>
		<link>http://www.turnleafdesign.com/if-else-and-nothing-else</link>
		<comments>http://www.turnleafdesign.com/if-else-and-nothing-else#comments</comments>
		<pubDate>Sat, 19 Sep 2009 19:52:03 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Noob Corner]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=81</guid>
		<description><![CDATA[When I was still very new to programming I had a bad habit of writing bloated code. One of my worse areas was when it came to the usage of If statements. Often times I would write a whole if/else block when I could had just as easily gotten the same results in just one [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fif-else-and-nothing-else"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fif-else-and-nothing-else" height="61" width="51" /></a></div><p>When I was still very new to programming I had a bad habit of writing bloated code. One of my worse areas was when it came to the usage of If statements. Often times I would write a whole if/else block when I could had just as easily gotten the same results in just one line of code.<span id="more-81"></span></p>
<blockquote><p>public class IfExample {</p>
<p>public static void main(String[] args){<br />
boolean getBoolValue;<br />
int a = 1, b = 2;</p>
<p>if(a &gt; b){<br />
getBoolValue = true;<br />
} else{<br />
getBoolValue = false;<br />
}<br />
}</p></blockquote>
<p>Instead of writing the whole if/else statement instead you can just directly take the result of the test condition.</p>
<blockquote><p>getBoolValue = a &gt; b;</p></blockquote>
<p>Some prefer to put parentheses around the comparison, however they are optional. I personally prefer a more minimalist code style.</p>
<h3>Be the ternary</h3>
<p>So what if you need something other than a boolean value? Enter the Java ternary operator. Which looks like this:</p>
<blockquote><p>String isEven = (3 % 2 == 0) ? "Yes" : "No";</p></blockquote>
<p>The element before the “?” is the test condition that is to be performed. The element before the “:” is the value that will be returned if the test condition is true and the element after the “:” is what will be returned if the test condition is false.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x60, created 9/14/09 */
google_ad_slot = "1115297999";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Java' rel='tag' target='_blank'>Java</a>, <a class='technorati-link' href='http://technorati.com/tag/Programming' rel='tag' target='_blank'>Programming</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/if-else-and-nothing-else/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Foreach isn&#8217;t a reach in pre-1.5</title>
		<link>http://www.turnleafdesign.com/foreach-isnt-a-reach-pre-1-5</link>
		<comments>http://www.turnleafdesign.com/foreach-isnt-a-reach-pre-1-5#comments</comments>
		<pubDate>Sat, 19 Sep 2009 03:10:47 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=69</guid>
		<description><![CDATA[Developers living in the post 1.5 world are spoiled. With the very sweet foreach loop life is easy when you need to iterate through a list of objects. While us poor developers still living working with 1.4 or lower may not be able to totally match the 1.5 foreach loop we can certainly come close! [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fforeach-isnt-a-reach-pre-1-5"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fforeach-isnt-a-reach-pre-1-5" height="61" width="51" /></a></div><p>Developers living in the post 1.5 world are spoiled. With the very sweet <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html">foreach</a> loop life is easy when you need to iterate through a list of objects. While us poor developers still living working with 1.4 or lower may not be able to totally match the 1.5 foreach loop we can certainly come close! While there are several ways to implement foreach functionality in 1.4 or below I will focus on the way I prefer to do it as I think it is the best way.</p>
<p><span id="more-69"></span></p>
<blockquote><p>public class ForeachExample {</p>
<p>public static void main(String[] args) {<br />
List personList = new ArrayList();</p>
<p>Person joe = new Person();<br />
joe.setFirstName("Joe");<br />
joe.setLastName("Smith");</p>
<p>Person cindy = new Person();<br />
cindy.setFirstName("Cindy");<br />
cindy.setLastName("Doe");</p>
<p>personList.add(joe);<br />
personList.add(cindy);</p>
<p>for(Iterator iter = personList.iterator(); iter.hasNext();){<br />
Person person = (Person)iter.next();<br />
if(person.getFirstName().equals("Joe")){<br />
iter.remove();<br />
continue;<br />
} else if(person.getFirstName().equals("Cindy")){<br />
System.out.println(person.getFirstName() + " wins again!");<br />
}<br />
System.out.println(person.getFirstName());<br />
}<br />
//Prints "Cindy wins again!"<br />
}</p>
<p>}</p></blockquote>
<h3>Iterate? Can you please elaborate...</h3>
<p>Ok so there is quite a bit happening there. First the for loop declaration. In the first section (called the initialization statement) I'm declaring an Iterator object on personList (any class that extends the Collection class can invoke the .iterator() method). An Iterator holds all the values of a collection and gives you tools for moving through and manipulating the list (Note: you can only move forward). I am then setting up the condition for when the for loop should run, in this case when my Iterator object returns false after the last member of my list the program will drop out of the loop. Usually there would be a next statement in a for loop declaration, however it is optional and typically isn't necessary in a foreach loop.<br />
Inside the loop we are assigning a person object to the current iter element, which is of course based on our list we declared earlier. Because an Iterator doesn't know what it holds you must cast the object type when you retrieve it from the Iterator (this issue is solved in 1.5 with parameterization). Next we have have an if statement checking for the name “Joe” in the firstName attribute of a person object, if true the “iter.remove()” method is called. This is a handy method which removes the current element from the Iterator object and also from the underlying list. So if I was to attempt to iterate through the personList again, all person objects with the firstName of “Joe” will have been removed. If you haven't already been exposed to it, the continue statement ends the current iteration of the loop. It's not really necessary here, but I added as it's a common practice.</p>
<h3>That's all nice but why?</h3>
<p>I choose to use the for loop method for imitating a foreach loop because; it keeps the code clean by putting all the loop declaration stuff into one place and the Iterator object is dropped from memory at the same time the for loop goes out of scope. The other way of handling a for each loop in pre-1.5 Java would be the following:</p>
<blockquote><p>Iterator iter = personList.iterator();<br />
while(iter.hasNext()){<br />
Person person = (Person)iter.next();<br />
if(person.getFirstName().equals("Joe")){<br />
iter.remove();<br />
continue;<br />
} else if(person.getFirstName().equals("Cindy")){<br />
System.out.println(person.getFirstName() + " wins again!");<br />
}<br />
System.out.println(person.getFirstName());<br />
}<br />
//Prints "Cindy wins again!"</p></blockquote>
<p>To me the code doesn't look as clean and the program holds on to the Iterator object even though it is no longer useful (remember you cannot re-iterate through an Iterator object). It's a matter of preference, but using the for loop method will always be the better choice from a strictly programmatic perspective.<br />
<script type="text/javascript"><!--
google_ad_client = "pub-3063474103916505";
/* 468x60, created 9/14/09 */
google_ad_slot = "1115297999";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></p>

<!-- start wp-tags-to-technorati 1.01 -->

<p class='technorati-tags'>Technorati Tags: <a class='technorati-link' href='http://technorati.com/tag/Java' rel='tag' target='_blank'>Java</a>, <a class='technorati-link' href='http://technorati.com/tag/Programming' rel='tag' target='_blank'>Programming</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/foreach-isnt-a-reach-pre-1-5/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
