<?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; Java</title>
	<atom:link href="http://www.turnleafdesign.com/tag/java/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>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>Link Dump 10/13</title>
		<link>http://www.turnleafdesign.com/link-dump-1013</link>
		<comments>http://www.turnleafdesign.com/link-dump-1013#comments</comments>
		<pubDate>Wed, 14 Oct 2009 01:51:48 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Link Dump]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=224</guid>
		<description><![CDATA[http://www.codeigniter.com – An excellent and lightweight framework for developing PHP applications
http://sites.google.com/site/yacoset/ - I may not agree with everything the author says and frankly he probably doesn't care. But there is plenty of good information on his site none the less.
http://solitarygeek.com/ - If you like my site then you will probably love this one. Similar 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%2Flink-dump-1013"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Flink-dump-1013" height="61" width="51" /></a></div><p><a href="http://www.codeigniter.com " target="_blank">http://www.codeigniter.com </a>– An excellent and lightweight framework for developing PHP applications<a href="http://sites.google.com/site/yacoset/" target="_blank"></a></p>
<p><a href="http://sites.google.com/site/yacoset/" target="_blank">http://sites.google.com/site/yacoset/</a> - I may not agree with <a href="http://www.turnleafdesign.com/?p=144" target="_blank">everything the author says</a> and frankly he probably <a href="http://sites.google.com/site/yacoset/Home/how-to-read-this-site" target="_blank">doesn't care</a>. But there is plenty of good information on his site none the less.</p>
<p><a href="http://solitarygeek.com/" target="_blank">http://solitarygeek.com/</a> - If you like my site then you will probably love this one. Similar in writing style and purpose, just a more mature blog written by a more experienced developer.<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/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></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/link-dump-1013/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Link Dump 10/6</title>
		<link>http://www.turnleafdesign.com/link-dump-106</link>
		<comments>http://www.turnleafdesign.com/link-dump-106#comments</comments>
		<pubDate>Wed, 07 Oct 2009 03:22:07 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Link Dump]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=177</guid>
		<description><![CDATA[http://sourcemaking.com/ - Co-authored by Martin Fowler, a bunch of useful information and best practices on this site.
http://www.pbell.com/index.cfm/design-patterns -A wealth of information covering many different areas of programming. Definitely something here for everybody.
http://marxsoftware.blogspot.com/ - A well established blog with hundreds of articles covering mostly Java.







Technorati Tags: Best practices, Java, Programming


]]></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%2Flink-dump-106"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Flink-dump-106" height="61" width="51" /></a></div><p><a href="http://sourcemaking.com/" target="_blank">http://sourcemaking.com/</a> - Co-authored by Martin Fowler, a bunch of useful information and best practices on this site.</p>
<p><a href="http://www.pbell.com/index.cfm/design-patterns" target="_blank">http://www.pbell.com/index.cfm/design-patterns </a>-A wealth of information covering many different areas of programming. Definitely something here for everybody.</p>
<p><a href="http://marxsoftware.blogspot.com" target="_blank">http://marxsoftware.blogspot.com/</a> - A well established blog with hundreds of articles covering mostly Java.<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/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></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/link-dump-106/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Link Dump 9/28</title>
		<link>http://www.turnleafdesign.com/link-dump-928</link>
		<comments>http://www.turnleafdesign.com/link-dump-928#comments</comments>
		<pubDate>Wed, 30 Sep 2009 04:13:59 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Link Dump]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=135</guid>
		<description><![CDATA[http://www.javaworld.com/ - An excellent Java resource
http://onjava.com/ - A blog covering java (obviously) supported by O'Reilly Media
http://martinfowler.com/ - The website for one of the most respected voices in OO-development







Technorati Tags: Java


]]></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%2Flink-dump-928"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Flink-dump-928" height="61" width="51" /></a></div><p><a href="http://www.javaworld.com/" target="_blank">http://www.javaworld.com/</a> - An excellent Java resource</p>
<p><a href="http://onjava.com/" target="_blank">http://onjava.com/</a> - A blog covering java (obviously) supported by O'Reilly Media</p>
<p><a href="http://martinfowler.com/" target="_blank">http://martinfowler.com/</a> - The website for one of the most respected voices in OO-development<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/Java' rel='tag' target='_blank'>Java</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/link-dump-928/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>
		<item>
		<title>Link Dump 9/17</title>
		<link>http://www.turnleafdesign.com/link-dump-917</link>
		<comments>http://www.turnleafdesign.com/link-dump-917#comments</comments>
		<pubDate>Fri, 18 Sep 2009 03:55:58 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Link Dump]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Open source]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web design]]></category>
		<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=65</guid>
		<description><![CDATA[http://www.sixrevisions.com/ - A very active website that focuses on web design.
http://www.net.tutsplus.com/ - Has excellent tutorials on web design and development
http://java.sun.com/blueprints/corej2eepatterns/Patterns/index.html – An absolute must check out for all Java developers. Focuses on best practices for Java developers. Though I wouldn't recommend it for the very new as the concepts may be a bit advanced.
http://www.ohloh.net/ - [...]]]></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%2Flink-dump-917"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Flink-dump-917" height="61" width="51" /></a></div><p><a href="http://www.sixrevisions.com/">http://www.sixrevisions.com/</a> - A very active website that focuses on web design.</p>
<p><a href="http://net.tutsplus.com/">http://www.net.tutsplus.com/</a> - Has excellent tutorials on web design and development</p>
<p><a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/index.html">http://java.sun.com/blueprints/corej2eepatterns/Patterns/index.html</a> – An absolute must check out for all Java developers. Focuses on best practices for Java developers. Though I wouldn't recommend it for the very new as the concepts may be a bit advanced.</p>
<p><a href="http://www.ohloh.net/">http://www.ohloh.net/</a> - A very good place to start if you are looking to contribute to an open source project.</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/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/Open+source' rel='tag' target='_blank'>Open source</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/Web+design' rel='tag' target='_blank'>Web design</a>, <a class='technorati-link' href='http://technorati.com/tag/Web+development' rel='tag' target='_blank'>Web development</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/link-dump-917/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Link Dump</title>
		<link>http://www.turnleafdesign.com/link-dump</link>
		<comments>http://www.turnleafdesign.com/link-dump#comments</comments>
		<pubDate>Tue, 15 Sep 2009 23:27:11 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Link Dump]]></category>
		<category><![CDATA[Best practices]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Web design]]></category>
		<category><![CDATA[Web development]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=43</guid>
		<description><![CDATA[http://www.smashingmagazine.com/ - An excellent with a focus on front end web development. Frequently updated with very well written articles.
http://www.alistapart.com/ - Another excellent website focusing on web development. However there is more of an emphasis of best practices, growing trends, and new ideas, instead of just the latest technologies.
http://www.javamex.com/ - A java site that does a [...]]]></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%2Flink-dump"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Flink-dump" height="61" width="51" /></a></div><p><a href="http://www.smashingmagazine.com/">http://www.smashingmagazine.com/</a> - An excellent with a focus on front end web development. Frequently updated with very well written articles.</p>
<p><a href="http://www.alistapart.com/">http://www.alistapart.com/</a> - Another excellent website focusing on web development. However there is more of an emphasis of best practices, growing trends, and new ideas, instead of just the latest technologies.</p>
<p><a href="http://www.javamex.com/">http://www.javamex.com/</a> - A java site that does a really good job of getting down into the nuts a bolts of how Java works.</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/Java' rel='tag' target='_blank'>Java</a>, <a class='technorati-link' href='http://technorati.com/tag/Web+design' rel='tag' target='_blank'>Web design</a>, <a class='technorati-link' href='http://technorati.com/tag/Web+development' rel='tag' target='_blank'>Web development</a></p>

<!-- end wp-tags-to-technorati -->
]]></content:encoded>
			<wfw:commentRss>http://www.turnleafdesign.com/link-dump/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How Java handles objects</title>
		<link>http://www.turnleafdesign.com/how-objects-work-in-java</link>
		<comments>http://www.turnleafdesign.com/how-objects-work-in-java#comments</comments>
		<pubDate>Tue, 15 Sep 2009 04:14:23 +0000</pubDate>
		<dc:creator>Billy Korando</dc:creator>
				<category><![CDATA[Noob Corner]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.turnleafdesign.com/?p=5</guid>
		<description><![CDATA[How Java handles objects had always been a thorny issue for me. I don't know if it was a case of never being taught properly or my personal inability to learn, but I either way by the time I began my professional development career I only had very loose understanding of how Java handles objects. [...]]]></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%2Fhow-objects-work-in-java"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.turnleafdesign.com%2Fhow-objects-work-in-java" height="61" width="51" /></a></div><p>How Java handles objects had always been a thorny issue for me. I don't know if it was a case of never being taught properly or my personal inability to learn, but I either way by the time I began my professional development career I only had very loose understanding of how Java handles objects. This gap in my knowledge impacted my ability to be an effective developer; my code had more bugs and implementing changes was more difficult. I remember many of my friends back in school also having trouble here, so I will spend my first real post (yay!) covering this important subject.<span id="more-5"></span></p>
<h3>All object variables are pointers</h3>
<p>Probably one of the first things you learned, or at least heard, about Java, was all object variables are pointers, but what does this mean and what are the implications? In simplest terms it means that a variable that holds an object doesn't actually store the value of the object, but its location in memory. Take for example the code snippet below:</p>
<p>String name = “Bob”;</p>
<p>The variable “name” doesn't hold the value “Bob,” but the location of where “Bob” is stored in memory. It's a difficult concept to grasp, I hope to make it easier to understand as well as go over the significance of this characteristic below.</p>
<h3>The implications</h3>
<p>So an object variable holds reference to an address in memory, but how will it effect your day to day programming? Well probably the first problem every programmer runs into when working with objects is comparing two Strings using the “==” operator instead of “.equals().” Using the “==” operator doesn't work as excepted on Strings (or any object), because like stated previously object variables do not contain the value of an object, but the address to where the value is stored. So when you are performing this operation: (name == “Bob”), you are actually comparing the the addresses in memory of the two objects, not their values. Whereas with name.equals(“Bob”) you are retrieving the value stored at the memory address the name variable references and comparing it to the String object passed into the equals(String) method. So while comparing two strings, or any other object requires more work than comparing two primitive data types like int or char there are some advantages.</p>
<h3>Passing by reference can often be used in place of returning</h3>
<p>Before I fully understood objects, if I wanted to use a method to manipulate an object I would often have that method returning a value. An example of this:</p>
<blockquote><p>public class ObjectExample {</p>
<p>public static void main(String args[]){<br />
Person a = new Person()<br />
a = changeFirstName(a);<br />
System.out.println(a.getFirstName());<br />
}</p>
<p>public static Person changeFirstName(Person a){<br />
a.setFirstName("Joe");<br />
//Prints Joe<br />
return a;<br />
}<br />
}</p></blockquote>
<p>While there is technically nothing wrong with this behavior, it is not the most efficient or readable way of handling this scenario. Also as you will likely notice in my next example the return statement is largely redundant. So here is an example of passing by reference:</p>
<blockquote><p>public class ObjectExample {</p>
<p>public static void main(String args[]){<br />
Person a = new Person();<br />
changeFirstName(a);<br />
System.out.println(a.getFirstName());<br />
//Prints Joe<br />
}</p>
<p>public static void changeFirstName(Person a){<br />
a.setFirstName("Joe");<br />
}<br />
}</p></blockquote>
<p>This code prints the name “Joe”, because remember you are not passing the value of the object, but its address in memory. So the method changeFirstName(Person) is manipulating the value stored at the address of the Person object passed in.</p>
<h3>Remember</h3>
<p>When you assign an object variable to another object variable you are not copying the value of the assigner variable to the assignee, but the reference. What this means is when you change the value of either variable, you change the value for both variables as shown in the example below:</p>
<blockquote><p>public class ObjectExample {</p>
<p>public static void main(String args[]){<br />
Person a = new Person();<br />
Person b = a;</p>
<p>a.setFirstName("Joe");</p>
<p>System.out.println(a.getFirstName());<br />
//prints Joe<br />
System.out.println(b.getFirstName());<br />
//prints Joe<br />
}<br />
}</p></blockquote>
<p>That sums up a fairly basic overview of how Java handles objects. If you have any questions or comments please leave a comment and I will try to respond as best I can.<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/how-objects-work-in-java/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
