<?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"
	>

<channel>
	<title>// Coding Without Comments</title>
	<atom:link href="http://www.codingwithoutcomments.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.codingwithoutcomments.com</link>
	<description>Perpetually In Beta.</description>
	<pubDate>Tue, 06 Jan 2009 16:08:40 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.3</generator>
	<language>en</language>
			<item>
		<title>Destination Seattle Day 5</title>
		<link>http://www.codingwithoutcomments.com/2009/01/06/destination-seattle-day-5/</link>
		<comments>http://www.codingwithoutcomments.com/2009/01/06/destination-seattle-day-5/#comments</comments>
		<pubDate>Tue, 06 Jan 2009 16:08:40 +0000</pubDate>
		<dc:creator>codingwithoutcomments</dc:creator>
		
		<category><![CDATA[Road Trip]]></category>

		<guid isPermaLink="false">http://www.codingwithoutcomments.com/?p=430</guid>
		<description><![CDATA[Destination Seattle Day 5
Moab Utah to Flagstaff Arizona
Total Distance: 318 miles
Woke up to a (freezing) cold morning in Moab, Utah at the Lazy Lizard.  After a quick stop by the local drug store, we headed south for Flagstaff and stopped a few times along the way to take pictures or just hang out and take [...]]]></description>
			<content:encoded><![CDATA[<p>Destination Seattle Day 5<a href="http://maps.google.com/maps?f=d&amp;saddr=Moab,+UT&amp;daddr=Flagstaff,+AZ&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=37.0625,-95.677068&amp;sspn=57.249013,87.451172&amp;ie=UTF8&amp;t=h&amp;z=8"><br />
Moab Utah to Flagstaff Arizona</a><br />
Total Distance: 318 miles</p>
<div id="attachment_426" class="wp-caption alignnone" style="width: 310px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/day5hostel.jpg"><img class="size-medium wp-image-426" title="day5hostel" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/day5hostel-300x225.jpg" alt="The Lazy Lizard in Moab, Utah" width="300" height="225" /></a><p class="wp-caption-text">The Lazy Lizard in Moab, Utah</p></div>
<p>Woke up to a (freezing) cold morning in Moab, Utah at the Lazy Lizard.  After a quick stop by the local drug store, we headed south for Flagstaff and stopped a few times along the way to take pictures or just hang out and take in some of the breathtaking views.</p>
<div id="attachment_427" class="wp-caption alignnone" style="width: 310px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/ontheroad.jpg"><img class="size-medium wp-image-427" title="ontheroad" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/ontheroad-300x198.jpg" alt="The Road To Flagstaff" width="300" height="198" /></a><p class="wp-caption-text">The Road To Flagstaff</p></div>
<p>In Mexican Hat, Utah (yes, this is a real place) we stopped and made friends with then nicest dog in the world.  Since this is Native American country, there are many dogs running free round these parts.</p>
<div id="attachment_428" class="wp-caption alignnone" style="width: 235px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/day5dog.jpg"><img class="size-medium wp-image-428" title="day5dog" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/day5dog-225x300.jpg" alt="Dog and Jason" width="225" height="300" /></a><p class="wp-caption-text">Dog in Mexican Hat, Utah and Jason</p></div>
<p>On the Utah/Arizona border, we stopped momentarily at the famous Monument Valley, Utah.</p>
<div id="attachment_429" class="wp-caption alignnone" style="width: 510px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/monumentvalley.jpg"><img class="size-full wp-image-429" title="monumentvalley" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/monumentvalley.jpg" alt="Monument Valley" width="500" height="155" /></a><p class="wp-caption-text">Monument Valley</p></div>
<p>We arrived in Flagstaff around 3:30 in the afternoon and checked into the Grand Canyon International hostel.  We got a private room with a set of bunk-beds and a private bathroom.  The room is very nice.  It has hardwood floors, a gas heater, and a great location in downtown historic flagstaff.</p>
<div id="attachment_433" class="wp-caption alignnone" style="width: 310px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/day5room.jpg"><img class="size-medium wp-image-433" title="day5room" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/day5room-300x225.jpg" alt="Jason writing a postcard in room" width="300" height="225" /></a><p class="wp-caption-text">Jason writing a postcard in room</p></div>
<p>Right around the corner from the hostel is Macy's a Vegetarian cafe where we had a late light lunch of Red-Bean Soup.  We then (attempted) to walk around Flagstaff, but the temperature was dropping and it started to snow.</p>
<div id="attachment_432" class="wp-caption alignnone" style="width: 235px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/day5unicorn.jpg"><img class="size-medium wp-image-432" title="day5unicorn" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/day5unicorn-225x300.jpg" alt="The last unicorn a.k.a. giant icicle hilarity" width="225" height="300" /></a><p class="wp-caption-text">The last unicorn a.k.a. giant icicle hilarity</p></div>
<p>After a quick stop at Wal-Mart for some $5 DVDs, we grabbed some Thai for dinner.  It was Aroy-Ma!  (Very Delicious)</p>
<p>Tomorrow:  <a href="http://maps.google.com/maps?f=d&amp;saddr=Flagstaff,+AZ&amp;daddr=Center+Loop+Rd,+Grand+Canyon+National+Park,+AZ+86001+(Grand+Canyon+National+Park)&amp;hl=en&amp;geocode=%3BCVf73XHP4RtbFdAvJgIdqO9Q-SGyLDS-E3Di4Q&amp;mra=pe&amp;mrcr=0&amp;sll=35.701917,-112.151184&amp;sspn=1.860114,2.732849&amp;ie=UTF8&amp;ll=35.689649,-111.924591&amp;spn=0.930215,1.366425&amp;t=h&amp;z=10">Flagstaff to the South Rim of the Grand Canyon!</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codingwithoutcomments.com/2009/01/06/destination-seattle-day-5/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Destination Seattle Day 3 and 4</title>
		<link>http://www.codingwithoutcomments.com/2009/01/05/destination-seattle-day-3-and-4/</link>
		<comments>http://www.codingwithoutcomments.com/2009/01/05/destination-seattle-day-3-and-4/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 05:02:58 +0000</pubDate>
		<dc:creator>codingwithoutcomments</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.codingwithoutcomments.com/?p=418</guid>
		<description><![CDATA[Destination Seattle Day 3 and 4
Denver to Winter Park, CO
Winter Park to Grand Junction, CO
Grand Junction CO to Moab, Utah

Saturday morning we woke up and dined at Watercourse Foods again for breakfast.  Then, because of an impending snow storm in Denver, we rushed up to Winter Park, CO after a brief car tour of Denver.  [...]]]></description>
			<content:encoded><![CDATA[<p>Destination Seattle Day 3 and 4<br />
<a href="http://maps.google.com/maps?f=d&amp;hl=en&amp;geocode=&amp;saddr=Denver,+CO&amp;daddr=Winter+Park,+CO&amp;sll=37.0625,-95.677068&amp;sspn=57.249013,87.451172&amp;ie=UTF8&amp;z=10">Denver to Winter Park, CO</a><br />
<a href="http://maps.google.com/maps?f=d&amp;saddr=Winter+Park,+CO&amp;daddr=Grand+Junction,+CO&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=39.80638,-105.40181&amp;sspn=0.879849,1.366425&amp;ie=UTF8&amp;z=8">Winter Park to Grand Junction, CO</a><br />
<a href="http://maps.google.com/maps?f=d&amp;saddr=Grand+Junction,+CO&amp;daddr=Moab,+Utah&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=39.50447,-107.108545&amp;sspn=3.534658,5.465698&amp;ie=UTF8&amp;z=10">Grand Junction CO to Moab, Utah<br />
</a><br />
Saturday morning we woke up and dined at Watercourse Foods again for breakfast.  Then, because of an impending snow storm in Denver, we rushed up to Winter Park, CO after a brief car tour of Denver.  On the way up, it started to snow.  I am now very glad I decided to trade in my Camry for a 4Runner several months ago.</p>
<div id="attachment_419" class="wp-caption alignnone" style="width: 310px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/snowroad.jpg"><img class="size-medium wp-image-419" title="snowroad" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/snowroad-300x225.jpg" alt="Drive up to Winter Park" width="300" height="225" /></a><p class="wp-caption-text">Drive up to Winter Park</p></div>
<p>We met up with my friend Rachel in Winter Park.  She was staying with a bunch of friends (18-20) in a small condo in Winter Park, a ski resort town in the mountains outside of Denver.  We ate lunch in a small bar, played in the snow for awhile (about 30 minutes &#8212; this was all we could stand &#8212; the temperature was a whopping 0 degrees F ), then went back to the Condo for a little R and R.</p>
<div id="attachment_420" class="wp-caption alignnone" style="width: 310px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/condoinwinterpark.jpg"><img class="size-medium wp-image-420" title="condoinwinterpark" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/condoinwinterpark-300x225.jpg" alt="Condo In Winter Park" width="300" height="225" /></a><p class="wp-caption-text">Condo In Winter Park</p></div>
<p>Around six in the pm, the tiny two bedroom condo started getting very crowded so we decided to hit the road again.  Little did we know, most of the towns between Winter Park and Moab are ski resort towns.  $200 and up for night in a mediocre hotel.  We finally found reasonable accommodation in Grand Junction, CO.  Super 8 whaaat?</p>
<p>The next morning, we drove about 2 beautiful hours to Moab, Utah.  Home of Arches National Park.  The park was absolutely mind blowing.</p>
<div id="attachment_421" class="wp-caption alignnone" style="width: 310px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/road-to-moab.jpg"><img class="size-medium wp-image-421" title="road-to-moab" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/road-to-moab-300x225.jpg" alt="Road To Moab" width="300" height="225" /></a><p class="wp-caption-text">Road To Moab</p></div>
<div id="attachment_422" class="wp-caption alignnone" style="width: 310px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/archesnationalpark.jpg"><img class="size-medium wp-image-422" title="archesnationalpark" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/archesnationalpark-300x225.jpg" alt="Me taking a picture of Jason taking a picture of the entrace to Arches" width="300" height="225" /></a><p class="wp-caption-text">Me taking a picture of Jason taking a picture of the entrance to Arches</p></div>
<div id="attachment_423" class="wp-caption alignnone" style="width: 310px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/meatdelicate.jpg"><img class="size-medium wp-image-423" title="meatdelicate" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/meatdelicate-300x225.jpg" alt="Me at the Delicate Arch" width="300" height="225" /></a><p class="wp-caption-text">Me at the Delicate Arch</p></div>
<p>After being floored by nature, we ate some mexican food then took in a showing of 'Yes Man' at the very very tiny local theatre.</p>
<p>Moab in January is a ghost town.  Almost every hotel we passed had a completely empty parking lot.  We are staying at the <a href="http://www.lazylizardhostel.com/">Lazy Lizard hostel</a> for a grand total of $11 per person.</p>
<p>Tomorrow:  <a href="http://maps.google.com/maps?f=d&amp;saddr=Moab,+Utah&amp;daddr=Flagstaff,+Az&amp;hl=en&amp;geocode=&amp;mra=pe&amp;mrcr=0&amp;sll=36.849813,-110.644231&amp;sspn=3.665774,5.465698&amp;ie=UTF8&amp;ll=36.734482,-110.324707&amp;spn=3.671247,5.465698&amp;t=h&amp;z=8">Moab, Utah to Flagstaff, Arizona. </a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codingwithoutcomments.com/2009/01/05/destination-seattle-day-3-and-4/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Destination Seattle Day 2 - Kingdom City MO, to Denver, CO</title>
		<link>http://www.codingwithoutcomments.com/2009/01/04/destination-seattle-day-2/</link>
		<comments>http://www.codingwithoutcomments.com/2009/01/04/destination-seattle-day-2/#comments</comments>
		<pubDate>Sun, 04 Jan 2009 15:27:41 +0000</pubDate>
		<dc:creator>codingwithoutcomments</dc:creator>
		
		<category><![CDATA[Road Trip]]></category>

		<guid isPermaLink="false">http://www.codingwithoutcomments.com/?p=410</guid>
		<description><![CDATA[Destination Seattle: Day 2
Kingdom City, MO to Denver, CO
Distance Covered: 747 miles
Day 2 was packed full of driving &#8212; across Kansas.  The state that never ends.  I just can't quit you Kansas.  Ever.  This is a record of what we saw:
wheat
more wheat
cows
wind turbines (ok these are pretty amazing)
endless nothing
and the occasional [...]]]></description>
			<content:encoded><![CDATA[<p>Destination Seattle: Day 2<br />
<a href="http://maps.google.com/maps?f=d&amp;saddr=Kingdom+City,+MO&amp;daddr=Denver,+CO&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=36.155315,-86.784225&amp;sspn=0,359.989733&amp;g=505+12th+Ave+South,+Nashville,+TN+37203&amp;ie=UTF8&amp;t=h&amp;z=6">Kingdom City, MO to Denver, CO</a><br />
Distance Covered: 747 miles</p>
<div id="attachment_414" class="wp-caption alignnone" style="width: 310px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/windpower.jpg"><img class="size-medium wp-image-414" title="windpower" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/windpower-300x199.jpg" alt="kansas wind turbines" width="300" height="199" /></a><p class="wp-caption-text">Kansas wind turbines</p></div>
<p>Day 2 was packed full of driving &#8212; across Kansas.  The state that never ends.  I just can't quit you Kansas.  Ever.  This is a record of what we saw:</p>
<p>wheat<br />
more wheat<br />
cows<br />
wind turbines (ok these are pretty amazing)<br />
endless nothing<br />
and the occasional oil well.</p>
<div id="attachment_412" class="wp-caption alignnone" style="width: 235px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/jasonnothing.jpg"><img class="size-medium wp-image-412" title="jasonnothing" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/jasonnothing-225x300.jpg" alt="endless nothing." width="225" height="300" /></a><p class="wp-caption-text">endless nothing.</p></div>
<p>We almost drove 80 miles out of the way to visit the largest ball of twine in the world in <a href="http://maps.google.com/maps?f=q&amp;hl=en&amp;geocode=&amp;q=cawker+city,+Kansas&amp;sll=38.013476,-98.382568&amp;sspn=6.965797,10.513916&amp;ie=UTF8&amp;ll=39.509471,-98.433123&amp;spn=0.213229,0.32856&amp;t=h&amp;z=12">Cawker City, Kansas</a>, but we decided to forgo the twine for our sanity.  We stopped in Topeka, KS and met some "real Topeka people" (Ok, only one person.  And it was just a female Wendy's employee that Jason held the door for going into Wendy's).</p>
<div id="attachment_411" class="wp-caption alignnone" style="width: 310px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/jasonrunning.jpg"><img class="size-medium wp-image-411" title="jasonrunning" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/jasonrunning-300x225.jpg" alt="In Topeka" width="300" height="225" /></a><p class="wp-caption-text">In Topeka</p></div>
<p>We drove into Denver bleary-eyed and exhausted around 8:20 in the PM.</p>
<div id="attachment_413" class="wp-caption alignnone" style="width: 235px"><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/welcometocolorado.jpg"><img class="size-medium wp-image-413" title="welcometocolorado" src="http://www.codingwithoutcomments.com/wp-content/uploads/2009/01/welcometocolorado-225x300.jpg" alt="Hug Me Please: Welcome to Colorado" width="225" height="300" /></a><p class="wp-caption-text">Hug Me Please: Welcome to Colorado</p></div>
<p>We stopped by my friend Rachel's house downtown who directed us to <a href="http://www.watercoursefoods.com/index.html">WaterCourse Foods</a>, an insanely good Vegeterarian/Gluten-Free eatery.  We then came back to Rachel's house and crashed.  Literally.</p>
<p>Tommorow: <a href="http://maps.google.com/maps?f=d&amp;saddr=Denver,+CO&amp;daddr=Winter+Park,+CO&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=39.743247,-104.973646&amp;sspn=0.00332,0.005134&amp;ie=UTF8&amp;t=h&amp;z=10">Denver, CO to Winter Park, CO </a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codingwithoutcomments.com/2009/01/04/destination-seattle-day-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Destination Seattle -  Day 1: Atlanta to Kingdom City, MO</title>
		<link>http://www.codingwithoutcomments.com/2009/01/02/destination-seattle-day-1-atlanta-to-kingdom-city-mo/</link>
		<comments>http://www.codingwithoutcomments.com/2009/01/02/destination-seattle-day-1-atlanta-to-kingdom-city-mo/#comments</comments>
		<pubDate>Fri, 02 Jan 2009 12:47:36 +0000</pubDate>
		<dc:creator>codingwithoutcomments</dc:creator>
		
		<category><![CDATA[Road Trip]]></category>

		<category><![CDATA[Travel]]></category>

		<guid isPermaLink="false">http://www.codingwithoutcomments.com/?p=408</guid>
		<description><![CDATA[View Larger Map
Day 1 is behind is.  We made it from Atlanta to about halfway between St. Louis and Kansas City.  I am updating from Super 8 Motel (classy) in Kingdom City, Missouri.  Yesterday, we stopped for lunch with Jason's friend Natalie in Nashville, TN at Ru-Sans one of our favorite sushi places.  Jason is [...]]]></description>
			<content:encoded><![CDATA[<p><iframe width="425" height="240" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps/sv?cbp=12,312.31522987917805,,0,-27.45384752428353&amp;cbll=38.623838,-90.184016&amp;panoid=&amp;v=1&amp;hl=en&amp;gl=us"></iframe><br /><small><a href="http://maps.google.com/maps?q=st.+louis+missouri&amp;ie=UTF8&amp;oe=utf-8&amp;client=firefox-a&amp;t=h&amp;layer=c&amp;cbll=38.623838,-90.184016&amp;panoid=Ssnvd0NQPURKLpEcKlFhFg&amp;cbp=12,312.31522987917805,,0,-27.45384752428353&amp;ll=38.637456,-90.194235&amp;spn=0.013495,0.020535&amp;z=14&amp;g=st.+louis+missouri&amp;iwloc=addr&amp;source=embed" style="color:#0000FF;text-align:left">View Larger Map</a></small></p>
<p>Day 1 is behind is.  We made it from <a href="http://maps.google.com/maps?f=d&amp;saddr=753+Edgewood+Ave+NE,+Atlanta,+GA+30307&amp;daddr=Kingdom+City,+MO&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=36.151824,-86.784225&amp;sspn=0.006766,0.010267&amp;g=505+12th+Ave+South,+Nashville,+TN+37203&amp;ie=UTF8&amp;t=h&amp;z=7" target="_blank">Atlanta to about halfway between St. Louis and Kansas City</a>.  I am updating from Super 8 Motel (classy) in <a href="http://tinyurl.com/a6vdkw" target="_blank">Kingdom City, Missouri</a>.  Yesterday, we stopped for lunch with Jason's friend Natalie in Nashville, TN at <a href="http://tinyurl.com/7d7bkm" target="_blank">Ru-Sans</a> one of our favorite sushi places.  Jason is taking lots of pictures and video along the way.  He wants to create a video akin to <a href="http://www.vimeo.com/1211060" target="_blank">Where the Hell is Matt?</a> without the dancing.  Late last night, we participated in a little drive-by tourism at <a href="http://tinyurl.com/8bj8p9" target="_blank">St. Louis' Great Arch</a>.  Jason ate his vegetarian sandwich there.  We filled up with gas for $1.32 a gallon! in <a href="http://maps.google.com/maps?f=q&amp;hl=en&amp;geocode=&amp;q=St.+Peters+Missouri&amp;sll=38.623962,-90.183957&amp;sspn=0.013495,0.020535&amp;ie=UTF8&amp;ll=38.78975,-90.617895&amp;spn=0.052249,0.08214&amp;t=h&amp;z=14" target="_blank">St. Peters, Mo</a> and we've been listening to lots (lots!) of XM radio.</p>
<p>Today:  <a href="http://maps.google.com/maps?f=d&amp;saddr=Kingdom+City,+MO&amp;daddr=Denver,+CO&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=36.350527,-88.187256&amp;sspn=7.120495,10.513916&amp;ie=UTF8&amp;t=h&amp;z=6" target="_blank">Kingdom City, MO to Denver, CO</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.codingwithoutcomments.com/2009/01/02/destination-seattle-day-1-atlanta-to-kingdom-city-mo/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Singleton I love you, but you're bringing me down</title>
		<link>http://www.codingwithoutcomments.com/2008/10/08/singleton-i-love-you-but-youre-bringing-me-down/</link>
		<comments>http://www.codingwithoutcomments.com/2008/10/08/singleton-i-love-you-but-youre-bringing-me-down/#comments</comments>
		<pubDate>Thu, 09 Oct 2008 02:58:15 +0000</pubDate>
		<dc:creator>codingwithoutcomments</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Code Smells]]></category>

		<category><![CDATA[design patterns]]></category>

		<category><![CDATA[love]]></category>

		<category><![CDATA[Single Responsability Principle]]></category>

		<category><![CDATA[singleton]]></category>

		<guid isPermaLink="false">http://www.codingwithoutcomments.com/?p=391</guid>
		<description><![CDATA[
It was love at first sight.  It was fall.  The leaves were changing color.  The air was cool and crisp, and my head was still reeling from reading about the Composite Pattern.  I turned the page on my copy of the GOF, and there the Singleton was in his black button-up-parka [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2008/10/singleton.jpg"><img class="aligncenter size-full wp-image-393" title="singleton" src="http://www.codingwithoutcomments.com/wp-content/uploads/2008/10/singleton.jpg" alt="" width="500" height="312" /></a></p>
<p>It was love at first sight.  It was fall.  The leaves were changing color.  The air was cool and crisp, and my head was still reeling from reading about the Composite Pattern.  I turned the page on my copy of the GOF, and there the <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton</a> was in his black button-up-parka and scarf saying:</p>
<p><strong>"Use me to restrict initiation of a Class to a single Object.  Use me to guarantee that one and only one instance of a given class exists during run-time."</strong></p>
<p>And that was it.  That was all he said.  He was a straight-shooter, a maverick.  He wasn't snobby or pretentious.  Definitely not an elitist.  His world-view was simple, concise.  Not like any other pattern I had met before.</p>
<p>OK.  Just to be clear.  I'm not that type of programmer.  I mean, I took it slow at first.  First we just went Logging together and then we took a weekend trip to the serial port.  But before I knew it, we were joined at the hip.  We were going everywhere together.</p>
<p>"<strong>Oh Singleton</strong>,"  I exclaimed one day after instantiating him from my constructor (not passed, mind you) of a helper class of methods, "<strong>You're too good to be true.</strong>"</p>
<p>Well, I think that kind of freaked Singleton out.</p>
<p>I knew something was up the day I tried to extend him and he barked at me and headed for the door.  I found out he started seeing other people (he did have global access to all my classes now that I think about it &#8212;  I knew I gave him too much space when I allowed him to control his own creation and life-cycle.)</p>
<p>I hired a Unit-Test to track him down, but that guy couldn't do anything.  When I finally did get a hold of him, he told me everything &#8212; all the gritty details.  His state, after all that time, had of course been retained.  I yelled and screamed and told him I didn't want to hear any more.  But he was relentless.  Unceasing.</p>
<p>It was at that moment that I ended my relationship with the Singleton.</p>
<p>I told him, "Singleton, I love you.  But you're bringing me down."</p>
<h2>Single(ton), again.</h2>
<p>Who among us hasn't smuggled into the break-room to nibble on a Singleton newton?  I, like you, drank the Singleton kool-aid.  At first Singletons were used appropriately.  Then, they were used inappropriately.  Then they were used <em>really</em> inappropriately.  And somewhere between the appropriate and the inappropriate, you, like me,  probably realized that something was amiss.  Something was aloof, a little bit off.</p>
<p>Then I, like you, read <a href="http://steve.yegge.googlepages.com/singleton-considered-stupid">"Singletons Considered Stupid"</a> by Steve Yeggee:</p>
<blockquote><p>Why is the Singleton so attractive? I'll be the first to admit: I liked it too. No, scratch that - I loved the Singleton. It felt like an old friend from the moment I laid eyes on it. It was simple and beautiful.</p>
<p>I'll tell you why: it's because the Singleton pattern is a throwback to non-OO programming. It's a lifeline for people who didn't understand a single word that the Gang of Four were trying to say.  It's almost exactly the way I programmed back when I didn't know jack squat about OOP. The only significant difference is that instead of having a file with a bunch of global functions in it, I have a file with a CLASS that has a bunch of global functions. No need to worry my little head about how many of them to have, since you only need one! It's OOP made easy.</p></blockquote>
<p>And my heart was broken.</p>
<p>Then I read <a href="http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/">article</a> after <a href="http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx">article</a> about why the Singleton was a piss poor Design Pattern.</p>
<p>I learned that Singletons were actually referred to as something called a "<a href="http://en.wikipedia.org/wiki/Code_smell">code smell.</a>" I didn't know if the smell was good or bad, but we figured it was bad.</p>
<p>I learned that Singletons violated something called the '<strong>Single Responsibility Principle</strong>' which states that every class you create should do one thing and one thing only because a Singleton has two distinct responsibilities: policing the instances of itself and providing configuration information.</p>
<p>I learned that Singletons were bad for memory management.  If no one uses it for awhile, its just going to sit and twiddle its thumbs.</p>
<p>I learned that the state of the Singleton never goes away.  Persistent state is the enemy of unit testing. One of the things that makes unit testing effective is that each test has to be independent of all the others.</p>
<p>I learned that Singleton's are kind of impossible to sub-class because they are static methods and static methods are about "as flexible as granite."</p>
<p>I learned that Singletons are (mostly) used as glorified globals and if you use them in your project, your project becomes almost impossible to unit-test because your "objects can secretly get hold of things which are not declared in their APIs, and, as a result, <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">Singletons make your APIs into pathological liars.</a>" Basically, when objects use Singletons they hide their dependencies.</p>
<p>I learned that maybe, just maybe you'll realize somewhere down the line that you actually need TWO instances of the Singleton.  Then what, buddy?</p>
<p>So I did what any completely sane Programmer would do.  I ripped RIPPED the Singleton Pattern out of GOF and burned the pages while doing a triple hail mary and beat on, boat against the current, swearing never NEVER to use another Singleton for as long as I shall live.</p>
<p>Then, three weeks later, after I sobered up, I realized that all the stuff I learned about why Singletons were the devil incarnate was  actually a form of "abstinence only" Design Pattern Education.  I knew that I could avoid all the aforementioned problems by simply <em>abstaining</em> completely from using Singletons, but what I didn't know was what happened on the day when I wanted to use a single instance of a class and thought that the Singleton might be the best tool for the job?</p>
<h2>Fine.  Go ahead, use it.</h2>
<p>First, before I answers the question posed above, let me address <em>you</em>.  I know you.  You're stubborn.  You're going to use that Singleton until someone rips it from your cold, dead claws.  If this is you, then just read on a little while longer then you can get back to uploading your favorite <a href="http://stackoverflow.com/questions/84556/whats-your-favorite-programmer-cartoon">programming cartoon to stackoverflow.</a></p>
<p>If you do use Singletons, try to use dependency injection instead of calling getInstance() from the constructor.</p>
<p>Use this:</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> MyConstructor<span style="color: #009900;">&#40;</span>Singleton singleton<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">singleton</span> <span style="color: #339933;">=</span> singleton;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>rather than this:</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> MyConstructor<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">singleton</span> <span style="color: #339933;">=</span> Singleton.<span style="color: #006633;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>At the very least, using dependency injection allows you to do some unit testing of the class by adhering to good encapsulation principles.  Using dependency injection might also stop Misko Hevrey from calling your API <a href="http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/">a pathological liar</a>.  But probably not.</p>
<h2>Check yo-self.</h2>
<p>For all the rest of you still reading, before using a Singleton ask yourself, "<strong>is a Singleton really the best tool for the job?</strong>"</p>
<p>On my quest for the truth I discovered that there are actually very few "acceptable" reasons to use a Singleton.</p>
<p>One reason that tends to come up over and over again on the internets is that of a "logging" class.   In this case, a Singleton can be used instead of a <strong>single instance of a class</strong> because a logging class usually needs to be used over and over again ad nauseam by every class in a project.  If every class uses this logging class, dependency injection becomes cumbersome.</p>
<p>Logging is a specific example an "acceptable" Singleton because it doesn't affect the execution of your code.  Disable logging, code execution remains the same.  Enable it, same same.  Misko puts it in the following way in <a href="http://misko.hevery.com/2008/08/25/root-cause-of-singletons/">Root Cause of Singletons</a>, "The information here flows one way: From your application into the logger. Even though loggers are global state, since no information flows from loggers into your application, loggers are acceptable."</p>
<p>I'm sure there are other valid reasons as well.  Alex Miller, in <a href="http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/">"Patterns I Hate"</a>, talks of service locators and client side UI's also being possibly "acceptable" choices.</p>
<h2>Single Instance Of A Class</h2>
<p>In most cases, though,  you probably got it wrong when you went to the ole' Singleton toolbox.  What you probably wanted was a simple <strong>single instance of a class</strong> instead of a Singleton.  There is absolutely nothing wrong with only wanting a single instance of a class.  There are, however, way better ways of managing these instances then a "glorified global".</p>
<p>How do you achieve a Single Configuration Object without using a Singleton?  Neal Ford in "The Productive Programmer" suggests "using a plain object plus a factory and delegating the individual responsibilities to each. The factory is responsible for the instance policing and the plain object deals only with configuration information and behavior."  By using this technique, your code no longer <strong>smells</strong> as it now adheres to the <strong>Single Responsibility Principle.</strong></p>
<p>Misko Hevrey (who does testing for google) goes into much greater detail about this technique in his two fantastic blog posts entitled <a href="http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/">"How to Think About the 'new' Operator with Respect to Unit Testing"</a> and <a href="http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/">"Where Have All the Singletons Gone?"</a></p>
<p>The idea is to have either classes with <strong>logic</strong> or classes with the <strong>new</strong> operator (factories).  When you need a single instance of a <strong>logic</strong> class, you call on the factory to build that class. Using this technique, all the dependencies are automatically injected into this single instance in proper order and returned to you.  All objects of a similar lifetime are grouped into this single factory.</p>
<p>Misko uses the example of building a "House."</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> House <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> Kitchen kitchen;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> Bedroom bedroom;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> isLocked;
&nbsp;
   <span style="color: #000000; font-weight: bold;">public</span> House<span style="color: #009900;">&#40;</span>Kitchen kitchen, Bedroom bedroom<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">kitchen</span> <span style="color: #339933;">=</span> kitchen;
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">bedroom</span> <span style="color: #339933;">=</span> bedroom;
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> isLocked<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> isLocked;
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">boolean</span> lock<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    kitchen.<span style="color: #006633;">lock</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
    isLocked <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">true</span>;
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Notice that in the House class, there are no instances of "new."  Remember, don't mix <strong>new</strong> and <strong>logic</strong>, baby.  Like J-Lo and Puffy.  All the dependencies needed to build a "House" are injected into the constructor.  All the "new" stuff is in the HouseFactory (seen below).</p>

<div class="wp_syntax"><div class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> HouseFactory <span style="color: #009900;">&#123;</span>
  House build<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
     Sink sink <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Sink;
     Dishwasher dishwasher <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Dishwasher;
     Refrigerator refrigerator <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Refrigerator;
     Kitchen kitchen <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Kitchen<span style="color: #009900;">&#40;</span>sink, dishwasher, refrigerator<span style="color: #009900;">&#41;</span>;
&nbsp;
	Bed bed <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Bed;
     Dresser dresser <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Dresser;
     Bedroom bedroom <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Bedroom<span style="color: #009900;">&#40;</span>bed, dresser<span style="color: #009900;">&#41;</span>;
&nbsp;
	House house <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> House<span style="color: #009900;">&#40;</span>kitchen, bedroom<span style="color: #009900;">&#41;</span>;
&nbsp;
    <span style="color: #000000; font-weight: bold;">return</span> house;
&nbsp;
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Main <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span>...<span style="color: #006633;">args</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    House house <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> HouseFactory<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">build</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
    house.<span style="color: #006633;">lock</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>In the "house" factory, when build() is called, kitchen is created and composed of sink, dishwasher, and refrigerator objects.  Bedroom is created and composed of created bed and dresser objects.  House is created, composed of kitchen and bedroom objects, then returned to the user.</p>
<p>Using this technique, you can see how easy it will be to achieve a single configuration object without the use of a Singleton.  A single instance of HouseBuilder is instantiated in the main and with that comes single instances of house, kitchen, bedroom, sink, dishwasher, refrigerator, bed, and dresser.</p>
<p>Using this technique solves the issue of global state because "there is no global state at all. Every object only has references to what it needs directly! No passing around of objects which are not directly needed by the code.  Dependencies are obvious since each object only asks for what it needs."</p>
<p>Using this technique solves the issue of memory management.  All classes will be created and used when needed.  No more Singletons sitting around and taking up memory while doing nothing at all.</p>
<p>Using this technique you can extend any of the classes you desire.  Static methods are nowhere.  No-sir.</p>
<p>Using this technique you can Unit-Test without fear of a wolf attack.</p>
<p><strong>Plus, Misko adds:</strong></p>
<blockquote><p>If an object needs a reference to a new dependency it simply declares it. This change only affects the corresponding factory, and as a result, it is very isolated.</p>
<p>All of the new operators end up in the factories; application logic is devoid of new operators.</p>
<p>You group all of the objects with the same lifetime into a single factory (If the factory gets too big you can break it up into more classes, but you can still think of it as a single factory)</p></blockquote>
<h2>Look Lisa, I'm learnding</h2>
<p>I loved Singletons.<br />
Then I <strong>loved</strong> Singletons a bit too much.</p>
<p>Then I read Steve Yegge.<br />
He broke my heart.</p>
<p>I sought answers.</p>
<p>If you are going to use Singletons I urge you to use Dependency Injection.<br />
But really you should know that their are very few reasons to actually use a Singleton.<br />
I think what you probably want is: a single instance of a class!<br />
If this is true: try using an object plus a factory.<br />
and Don't mix the "new" with the "logic" baby.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codingwithoutcomments.com/2008/10/08/singleton-i-love-you-but-youre-bringing-me-down/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Programming Paradigms - Lecture 6 - CS107 - Stanford University</title>
		<link>http://www.codingwithoutcomments.com/2008/10/04/programming-paradigms-lecture-6-cs107-stanford-university/</link>
		<comments>http://www.codingwithoutcomments.com/2008/10/04/programming-paradigms-lecture-6-cs107-stanford-university/#comments</comments>
		<pubDate>Sun, 05 Oct 2008 02:23:39 +0000</pubDate>
		<dc:creator>codingwithoutcomments</dc:creator>
		
		<category><![CDATA[Stanford CS107]]></category>

		<category><![CDATA[CS107]]></category>

		<category><![CDATA[generics]]></category>

		<category><![CDATA[Lecture 6]]></category>

		<category><![CDATA[Programming Paradigms]]></category>

		<category><![CDATA[stacks]]></category>

		<category><![CDATA[Stanford University]]></category>

		<category><![CDATA[static]]></category>

		<guid isPermaLink="false">http://www.codingwithoutcomments.com/?p=376</guid>
		<description><![CDATA[The following is a brief overview of Lecture 6 of the ‘Programming Paradigms,” a programming class taught at Standford University.  Screenshots and Code are included from the lecture.  The ‘Programming Paradigms’ lectures can be found in iTunes.  The link is on the Open Standford Website.  The following lecture covers Implementing an [...]]]></description>
			<content:encoded><![CDATA[<p>The following is a brief overview of Lecture 6 of the ‘Programming Paradigms,” a programming class taught at Standford University.  Screenshots and Code are included from the lecture.  The ‘Programming Paradigms’ lectures can be found in iTunes.  The link is on the <a href = "http://itunes.stanford.edu/">Open Standford Website</a>.  The following lecture covers Implementing an Int Specific and Generic Stack in C/C++.  </p>
<h2>Int Specific Stack</h2>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">stack.<span style="color: #007788;">h</span>
&nbsp;
<span style="color: #0000ff;">typedef</span> <span style="color: #0000ff;">struct</span><span style="color: #008000;">&#123;</span>
	<span style="color: #0000ff;">int</span> <span style="color: #000040;">*</span> elems;
	<span style="color: #0000ff;">int</span> loglength;
	<span style="color: #0000ff;">int</span> alloclength;
<span style="color: #008000;">&#125;</span> stack;
&nbsp;
<span style="color: #0000ff;">void</span> StackNew<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s<span style="color: #008000;">&#41;</span>
<span style="color: #0000ff;">void</span> StackDispose<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s<span style="color: #008000;">&#41;</span>
<span style="color: #0000ff;">void</span> StackPush<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s, <span style="color: #0000ff;">int</span> value<span style="color: #008000;">&#41;</span>
<span style="color: #0000ff;">int</span>  StackPop<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s<span style="color: #008000;">&#41;</span></pre></div></div>

<p>The last lecture was left off with header file for a int specific stack being defined which includes a strcut called 'stack' and four functions.  This lecture begins with defining StackNew and StackDispose for an int specific stack.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> StackNew<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength <span style="color: #000080;">=</span> <span style="color:#800080;">0</span>;
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>alloclength <span style="color: #000080;">=</span> <span style="color: #0000dd;">4</span>
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems <span style="color: #000080;">=</span> <span style="color: #0000dd;">malloc</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">4</span> <span style="color: #000040;">*</span> <span style="color: #0000dd;">sizeof</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
	<span style="color: #0000dd;">assert</span><span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color: #0000ff;">NULL</span><span style="color: #008000;">&#41;</span>;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>When a new stack is allocated, the length is set originally to zero (because the stack is empty).  Space is made for 4 elements, then malloc is used to allocate memory for those four elements.  Malloc goes to the heap and finds 16 bytes of space, puts a "little halo" around the space, and then returns the base address of the memory.  Assert confirms that elem is not equal to NULL just incase malloc fails for some reason.  Asserts should be used to you clearly know where the program failed.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> StackDispose<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #0000dd;">free</span><span style="color: #008000;">&#40;</span>s<span style="color: #008000;">&#41;</span>;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>StackDispose is trivial.  The opposite of malloc, free is used.  This gives the memory back to the heap.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> StackPush<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s, <span style="color: #0000ff;">int</span> value<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength <span style="color: #000080;">==</span> s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>alloclength<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#123;</span>
		s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>alloclength <span style="color: #000040;">*</span><span style="color: #000080;">=</span> <span style="color: #0000dd;">2</span>;
		s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems <span style="color: #000080;">=</span> <span style="color: #0000dd;">realloc</span><span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems, s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>alloclength <span style="color: #000040;">*</span> <span style="color: #0000dd;">sizeof</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>;
		<span style="color: #0000dd;">assert</span><span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color: #0000ff;">NULL</span><span style="color: #008000;">&#41;</span>;
	<span style="color: #008000;">&#125;</span>
&nbsp;
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elemns<span style="color: #008000;">&#91;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength<span style="color: #008000;">&#93;</span> <span style="color: #000080;">=</span> value;
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength++;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>In the function StackPush, you first want to check if you are out of memory to actually push value onto the Stack.  If the current length of the stack is already equal to the allocated length, more memory will have to be allocated for the stack, else bad things will happen.  </p>
<p>Actually, we want to go ahead and re-allocate the array. The previously allocated amount of memory is doubled.  Then realloc is called.  Realloc only exists in C, it doesn't exist in C++.  Jerry says that he'll explain in a few weeks why realloc doesn't exist in C++.  Realloc first sees if the memory can be allocated in place, meaning that realloc checks to see if the memory that comes after the previously allocated space in the heap is in use.  If it isn't, it uses that memory.  If it can't resize it in place, it copies all the elements over to a different block of memory, frees the old memory, and returns the address of the new memory.  </p>
<p>If realloc is called with the first parameter being equal to NULL, it functions the same as a malloc command.  This is useful if you don't want to call malloc once, then realloc every single time after that.  </p>
<p>The doubling strategy is really popular because it only comes up once every 2^n times.  512 bytes of memory not big enough?  Ok, let's allocate 1024.  And so on.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;"><span style="color: #0000ff;">int</span> StackPop<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span>s<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #0000dd;">assert</span><span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength<span style="color: #000080;">&gt;</span> <span style="color:#800080;">0</span><span style="color: #008000;">&#41;</span>;
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength--;
	<span style="color: #0000ff;">return</span> s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems<span style="color: #008000;">&#91;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength<span style="color: #008000;">&#93;</span>;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>First, make sure that their is at least one object on the stack.  Subtract one for loglength (the length of the stack), then return the new address of the stack which simulates the discarding of the last element on the stack.  </p>
<h2>Stack Using Generics</h2>
<p>Next, the exact same stack functions will be implemented generically, not just for stack integers.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">stack.<span style="color: #007788;">h</span>
typdef <span style="color: #0000ff;">struct</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #0000ff;">void</span> <span style="color: #000040;">*</span> elems;
    <span style="color: #0000ff;">int</span> elemSize;
    <span style="color: #0000ff;">int</span> loglength;
    <span style="color: #0000ff;">int</span> alloclength;
    <span style="color: #008080;">??</span> <span style="color: #000040;">-</span> Suspense Element
<span style="color: #008000;">&#125;</span> stack;
&nbsp;
<span style="color: #0000ff;">void</span> StackNew<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s, <span style="color: #0000ff;">int</span> elemSize<span style="color: #008000;">&#41;</span>;
<span style="color: #0000ff;">void</span> StackDispose<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s<span style="color: #008000;">&#41;</span>;
<span style="color: #0000ff;">void</span> StackPush<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s, <span style="color: #0000ff;">void</span> <span style="color: #000040;">*</span> elemAddr<span style="color: #008000;">&#41;</span>;
<span style="color: #0000ff;">void</span> StackPop<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s, <span style="color: #0000ff;">void</span> <span style="color: #000040;">*</span> elemAddr<span style="color: #008000;">&#41;</span>;</pre></div></div>

<p>The above is the setup for the stack functions that will be implemented generically.  Note that not all the information has yet been given as suspense element will be added later to the stack struct.  70% of the code for the generic stack functions is the same as the int specific stack functions.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> StackNew<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s, <span style="color: #0000ff;">int</span> elemSize<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #0000dd;">assert</span><span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elemSize <span style="color: #000080;">&gt;</span> <span style="color:#800080;">0</span><span style="color: #008000;">&#41;</span>;
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>length <span style="color: #000080;">=</span> <span style="color:#800080;">0</span>;
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>alloclength <span style="color: #000080;">=</span> <span style="color: #0000dd;">4</span>;
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elemSize <span style="color: #000080;">=</span> elemSize;
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems <span style="color: #000080;">=</span> <span style="color: #0000dd;">malloc</span><span style="color: #008000;">&#40;</span><span style="color: #0000dd;">4</span> <span style="color: #000040;">*</span> elemSize<span style="color: #008000;">&#41;</span>;
	<span style="color: #0000dd;">assert</span><span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems <span style="color: #000040;">!</span><span style="color: #000080;">=</span> <span style="color: #0000ff;">NULL</span><span style="color: #008000;">&#41;</span>;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The second parameter (elemSize) tells the length of a single element, so malloc is used to pre-allocate 4 elements on the stack of size elemSize.  Assert is used to make your life easier.  It checks to make sure actual memory was allocated and to make sure elemSize was not accidentally set to zero.</p>
<p><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2008/10/picture2.png"><img src="http://www.codingwithoutcomments.com/wp-content/uploads/2008/10/picture2-300x225.png" alt="" title="picture2" width="300" height="225" class="alignnone size-medium wp-image-377" /></a></p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> StackDispose<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span> s<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #0000dd;">free</span><span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems<span style="color: #008000;">&#41;</span>;
&nbsp;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>StackDispose is again trivial.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> StackPush<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span>s, <span style="color: #0000ff;">void</span> <span style="color: #000040;">*</span> elemAddr<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #0000ff;">if</span><span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength <span style="color: #000080;">==</span> s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>alloclength<span style="color: #008000;">&#41;</span>
		StackGrow<span style="color: #008000;">&#40;</span>s<span style="color: #008000;">&#41;</span>;
&nbsp;
	<span style="color: #0000ff;">void</span> <span style="color: #000040;">*</span> target <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span> s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems <span style="color: #000040;">+</span> s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength <span style="color: #000040;">*</span> s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elemSize;
	<span style="color: #0000dd;">memcpy</span><span style="color: #008000;">&#40;</span>target, elemAddr, s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elemSize<span style="color: #008000;">&#41;</span>;
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength++;
&nbsp;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>In StackPush, if the stack needs more memory allocated, StackGrow() is called to allocate that memory.  Target points to the block of memory already pre-allocated in the stack where the element will be copied..  Memcpy is used to do the actual copying of the element to that address.  Remember to cast s->elems as a char * to trick the compiler because it cannot cast as a void *.</p>
<p>The word static has like 80 or 85 meanings in C++.  Here is one more.  When you see the word static decorating the prototype of a c or c++ function such as:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">stack <span style="color: #0000ff;">void</span> StackGrow<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span>s<span style="color: #008000;">&#41;</span></pre></div></div>

<p>This means that it is a private function that should not be advertised outside this file.  In companies like Microsoft which deal with programs with tens of thousands of files, many times function names will conflict with each other if not made static.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;"><span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> StackGrow<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span>s<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>alloclength <span style="color: #000040;">*</span><span style="color: #000080;">=</span><span style="color: #0000dd;">2</span>;
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems <span style="color: #000080;">=</span> <span style="color: #0000dd;">realloc</span><span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems, s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>alloclength <span style="color: #000040;">*</span> s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elemSize<span style="color: #008000;">&#41;</span>;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>StackGrow re-allocates double the amount of memory just like the int specific version.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;"><span style="color: #0000ff;">void</span> StackPop<span style="color: #008000;">&#40;</span>stack <span style="color: #000040;">*</span>s, <span style="color: #0000ff;">void</span> <span style="color: #000040;">*</span> elemAddr<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #0000ff;">void</span> <span style="color: #000040;">*</span> source <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">char</span><span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span> s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elems <span style="color: #000040;">+</span> <span style="color: #008000;">&#40;</span>s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength <span style="color: #000040;">-</span> <span style="color: #0000dd;">1</span><span style="color: #008000;">&#41;</span> <span style="color: #000040;">*</span> s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elemSize;
	<span style="color: #0000dd;">memcpy</span><span style="color: #008000;">&#40;</span>elemAddr, source, s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>elemSize<span style="color: #008000;">&#41;</span>
	s<span style="color: #000040;">-</span><span style="color: #000080;">&gt;</span>loglength--;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>In StackPop(), source points to the last chunk of data in memory on the stack.  Memcpy copies that memory to the memory address, then the length of the stack is decremented thus "popping" off the memory from the stack.</p>
<p><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2008/10/picture3.png"><img src="http://www.codingwithoutcomments.com/wp-content/uploads/2008/10/picture3-300x225.png" alt="" title="picture3" width="300" height="225" class="alignnone size-medium wp-image-378" /></a></p>
<p>When dealing with generics, it is very easy to get the program to compile because the compiler looks at all the void * declarations and stamps them as "good."  However, when running a program implementing generics, it is very likely to crash.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codingwithoutcomments.com/2008/10/04/programming-paradigms-lecture-6-cs107-stanford-university/feed/</wfw:commentRss>
		</item>
		<item>
		<title>When is multi-threading not a good idea?</title>
		<link>http://www.codingwithoutcomments.com/2008/09/21/when-is-multi-threading-not-a-good-idea/</link>
		<comments>http://www.codingwithoutcomments.com/2008/09/21/when-is-multi-threading-not-a-good-idea/#comments</comments>
		<pubDate>Mon, 22 Sep 2008 03:23:14 +0000</pubDate>
		<dc:creator>codingwithoutcomments</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[GUI Programming]]></category>

		<category><![CDATA[Multi-Core]]></category>

		<category><![CDATA[Multi-Threading]]></category>

		<category><![CDATA[Parallel Data Computation]]></category>

		<category><![CDATA[QT]]></category>

		<category><![CDATA[resource contention]]></category>

		<category><![CDATA[Sequential Code]]></category>

		<category><![CDATA[thread contention]]></category>

		<category><![CDATA[threading]]></category>

		<category><![CDATA[threads]]></category>

		<category><![CDATA[When To Use Threads]]></category>

		<guid isPermaLink="false">http://www.codingwithoutcomments.com/?p=349</guid>
		<description><![CDATA["When all you have is a hammer, everything looks like a nail."
I was recently working on an application that sent and received messages over Ethernet and Serial. I was then tasked to add the monitoring of DIO discretes. I throught,
"No reason to interrupt the main thread which is involved in message processing, I'll just create [...]]]></description>
			<content:encoded><![CDATA[<h2><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2008/09/stop1.png"><img class="alignleft size-full wp-image-354" style="margin: 3px 6px;" title="stop1" src="http://www.codingwithoutcomments.com/wp-content/uploads/2008/09/stop1.png" alt="" width="221" height="253" /></a>"When all you have is a hammer, everything looks like a nail."</h2>
<p>I was recently working on an application that sent and received messages over Ethernet and Serial. I was then tasked to add the monitoring of DIO discretes. I throught,</p>
<p><strong>"No reason to interrupt the main thread which is involved in message processing, I'll just create another thread that monitors DIO."</strong></p>
<p>This decision, however, proved to be <strong>poor</strong>. Sometimes the main thread would be interrupted between a Send and a Receive Serial message. This interruption would disrupt the timing and alas, messages would be lost (forever).</p>
<p>So I found another way to monitor the DIO without using another thread, and Ethernet and Serial communication were restored to their correct functionality.</p>
<p>The whole fiasco, however, got me thinking. Are their any general guidelines about when not to use multiple-threads?</p>
<p>I asked my friends at <a href="http://stackoverflow.com/questions/93834/when-is-multi-threading-not-a-good-idea">stack-overflow</a> and scoured the internet for information.  The results may surprise you.</p>
<h2>Think twice, no three times before even thinking about using threads</h2>
<p>I heard this advice time and time again on blog after blog.  Before you thread, think.</p>
<p>I think the old programming wives tale puts it best: <strong> A Programmer had a problem.  He thought, 'I know, I'll use threads'  Now the programmer has two problems.</strong></p>
<p>Many think that if multiple threads are used, old-man-trouble gonna come round the corner and knock the sweet bejesus outta you.  There is good reason to fear old-man-trouble.  Using multiple threads adds a whole new layer of complexity to your code.  If something, somewhere goes wrong with you code down the line, that new layer of complexity makes your code just that much harder to debug and maintain.  Not to mention that multiple-threaded code is a good bit harder to scale.</p>
<p>In a recent project, I used two threads to implement a command processing routine.  Thread One sent Thread Two a command.  Thread Two executed that command.  Thread Two said to Thread one, "Give me another command."  Thread one sent Thread two another command.  And so on and so forth.  It took me a long time and many lines of code to get the two threads playing nicely.</p>
<p>Several weeks later, the code broke.  I stared at that code for &#8212; I kid you not &#8212;  two hours trying to figure out exactly what I had originally done.  Code should just not be that complex.  <strong>Remember, keep it simple</strong>.  I could have easily performed the same functionality with a single thread.</p>
<p>As Thomee on StackOverflow put it, <strong>"Don't use threads, unless there's a very compelling reason to use threads." </strong></p>
<p>So, when it comes to threads, ignore Bob Dylan's sweet sweet crooning, "Don't think twice it's alright&#8230;."</p>
<p>When it comes to everything else through, Dylan should prevail.</p>
<h2>Absolutely Never</h2>
<p>Fifel, in 'An American Tale' made  his sentiments on the word 'never' as his little mice lungs wailed, "Never, say never, say never my friend."  While I try to <em>never</em> adhere to absolutes, there are several cases where multiple-threads should absolutely <strong>never be used</strong>.</p>
<h3><strong>When bound by a single resource</strong></h3>
<p>Multiple threads should never be used when each thread is just going to be battling it out for the same single resource.  In his blog entry, <a href="http://www.yoda.arachsys.com/csharp/threads/whentouse.shtml">"When to use Threads"</a>, skeet expresses the pointlessness of using multiple-threads when sharing a single resource.</p>
<p>"If your application is bound by a single resource (i.e. the disk, or the CPU) and all the tasks you would use multiple threads for will all by trying to use that same resource, you'll just be adding contention."</p>
<p>When I was in elementary school, I certainly knew about the contention stemming from vying for the same resource.  Each day after P.E., we would all come pouring back into the building from being outside in the 99 degree heat for the last 30 minutes.  We were hot, sweaty, and thirsty, but our elementary school only had a single drinking fountain.  There was always a race to the fountain.</p>
<p>When we arrived, we would push, shove, grope, kick  &#8212; anything to get a drink of that cool refreshing beverage.  But no matter how hard we battled each other, ultimately only one person could drink at a time.  <strong>We were bound by a single resource</strong>.  And battling each other for water only slowed the process down.  A teacher would arrive 30 seconds later and make us form a single-file line.  Standing in line, we would tap our feet and clear our throats when we felt someone was taking just a little bit too long, drinking a little bit too much.  But in a short period of time everyone got their fill.</p>
<p>A few years ago, I was in the process of moving a large amount of music from one hard drive to another.  I selected all the folders at once (all 2000 or so of them) and dragged them over to the second drive.  The Windows File Copy routine booted up and showed '45 minutes' as the estimated amount of time to complete the job.</p>
<p>Well, I was in a rush.  And thinking that I was clever, I decided to cancel the operation and instead tried to parallel-ize the copying job.  As fast as I could click, I copied and pasted 10 folders at a time into the new drive.  When I got about 500 folders in, all the processes <strong>ground . to . a . halt</strong>.  The hard drive head was seeking all over the place and never making any progress on the copy operation.</p>
<p>At this point, I realized my stupidity.  The operation was bound by a single resource &#8212; the disk!  The hard-drive was my metaphorical elementary school water fountain.  And each copy process was pushing, shoving, and grouping for that single resource.</p>
<p>Understand how the resources you are using are bounded, and if those resources only have a single point of entry, there is absolutely no point in trying to use multiple-threads to complete the task at hand.<strong></strong></p>
<h3><strong>Sequential Code</strong></h3>
<p>Multiple Threads should also never be used when each step being executed relies heavily on the results from previously executed steps.  For example, the steps to drive a car are as follows:</p>
<ol>
<li>Turn On The Ignition</li>
<li>Put the car into 'Drive</li>
<li>Hit the Gas</li>
</ol>
<p>To drive a car, you must complete the above steps in order.<br />
Each step must be completed before the next step can be executed.<br />
If you try to complete any of these steps out of order, the results will not be what you desired.<br />
You simply cannot put the car into 'drive' without first turning on the ignition.</p>
<p>I guess you could technically reverse steps two and three by hitting the gas, then put the car into 'Drive', but only if you were filming a remake of Smokey and the Bandit or something.  Regardless, you would never try to complete all three steps at once.  That would be foolish.</p>
<p>starting with a<br />
b = functionX(a)<br />
c = functionY(b)<br />
d = functionZ(c)</p>
<p>Take a look at the code above.  I think we can agree that <em>most</em> code is sequential in nature.  You start with A.  You plug A into functionX, it returns B.  You plug B into functionY, it returns C. You plug C into function Z, it returns D.  Each step leads into the next.  FunctionY cannot be executed before B is computed.  FunctionZ cannot be executed before C is computed.  Trying to implement the above code with multiple-threads is like trying drive a car without turning on the ignition.  It is pointless.</p>
<p><strong>If your code must be completed sequentially, using multiple-threads is worthless.</strong></p>
<h2>When to (Maybe) Use Threads</h2>
<h3><strong>GUI Programming - Keeping a Process Responsive</strong></h3>
<p>One place multi-threading does actually come in handy is when programming a Graphical User Interface (GUI).  Multiple-Theads are sometimes used in GUIs to keep them responsive while the computer is chewing on user input.</p>
<p>For example, say you have a program that did nothing but compute the digits of pi.  Next, you add a GUI to the program that had a single Big Button that toggled between "Compute Digits of Pi" and "Stop Computing Digits of Pi." After clicking on "Computer Digits of Pi" and starting the program, if multiple threads are not employed to keep the GUI active while computation is taking place by the processor, "Stop Computing Digits of Pi" would never be able to be clicked.  <strong>The program could never be stopped</strong>.  The GUI would be frozen, indefinitely churning out digits of pi until the universe came to an end.</p>
<p>A Threading Rule Of Thumb:<strong> When programming a GUI, if the user input takes longer then one to two seconds to compute, consider using a second thread.</strong></p>
<p>Keeping the GUI responsive is very important and contributes to usability. Skeet delves more into this sentiment on <a href="http://www.yoda.arachsys.com/csharp/threads/whentouse.shtml">'When To Use Threads'</a> when he says that "the UI can easily become very unresponsive, which gives a horrible user experience.  (GUI) threading isn't used to get the job done quickly - it's used to get the job done while keeping the user satisfied with responsiveness.  You might be surprised just how quickly a user can notice an app becoming unresponsive.  Even if the user can't actually do anything but close the program or move the window around while they wait it gives a much more professional feel to a program if you don't end up with a big white box when you pass another window over it."</p>
<p>But, again let me emphasize that you should always think twice about using multiple-threads even in GUI applications.  Earlier this year, I developed a QT GUI application that interacted over Ethernet with big-hunking piece of hardware.  I would send a command to this hardware, the hardware would execute that command, then, after executing the command, the hardware would send back a response saying "Everythings OK!" or "FAIL!"  The hardware could take up to five minutes to respond to certain commands.</p>
<p>If I didn't want my GUI to freeze up while waiting for the hardware's response, one option would have been to spin the command/response process onto a separate thread.  But another less complex option would have been to use non-blocking calls to the ethernet API functions and a timer to periodically monitor the status of the ethernet ports to see if a message had been received or not.  Easy Right?</p>
<p>Whether or not you understand what non-blocking calls are, my point is this:  <strong>There is almost always more then one way to skin a cat.</strong> Think about that cat.  Wait, is the cat the thread?  Never-mind.</p>
<h3><strong>Data Analysis (Algorithm Processing) on Multi-Core Machines When Performance Matters</strong></h3>
<p>If you are working with multiple-processors, with data computation that can be parallelized, and are in the business of getting things done quickly, then guess what?  Multiple-threads are something you should consider.</p>
<p>With more than one processor, multi-threading is truly multi-threading &#8212;  meaning that two tasks can be (for-real) executed at the same time.  One task on each core (processor).  On a single core machine, multi-threading is a scam (a farce!).  The scheduler plays a game of red-light, green-light with the threads when more than one thread is used.  It decides which which task executes when.  If you set break  points and watch the scheduler switch back and forth between threads, it seems totally random.  You can give the scheduler general guidelines as to which thread is more important, but exactly <em>when</em> each thread executes is mostly out of your control.  Multiple-Cores give you much more control over schedule execution.</p>
<p>Data computation that can be parallelized is the opposite of the sequential code processing that was talked about above.  Parallel tasks can be divvied up and divided between multiple-cores.  The ordering of the execution does not matter.  If thread 4 finishes execution before thread 3, this is OK.  Think parallel complex data processing algorithms.  Think complex math stuff.</p>
<p>When coding-up these parallel data processing algorithms, something that you have try to be careful about is creating <strong>too many threads</strong>.  Say you get excited about your multiple-cores and parallel processes and start spinning threads off all over the place unbounded.  Then, instead of resource contention, you suffer from <strong>thread contention</strong> and your CPU's spend more time switching between threads then it does processing them.  Put an upper limit on the number of threads you create.  Google 'Thread Pools.'</p>
<p>But remember just because you have multi-core machine and are working with data computation that can be parallelized doesn't mean you should use multiple-threads.  Try it single threaded first.  Not fast enough?  Try two threads?  Still not fast enough?  Try three.  Take it slow.  Only add more complexity when absolutely necessary.</p>
<p>So, what have we learned?</p>
<h3>1.  Try not to use threads.<br />
2.  Think.<br />
3.  Keep it simple.<br />
4.  Sharing a single resource?  Don't use threads.<br />
5.  Sequential Code?  Don't use threads.<br />
6.  GUI programming?  Try not to use threads, but keep the GUI responsive.<br />
7.  Multiple-Cores?  Parallel Data Computation?  Don't use threads.<br />
8.  Multiple-Cores?  Parallel Data Computation?  The need for speed?  Use Threads.</h3>
]]></content:encoded>
			<wfw:commentRss>http://www.codingwithoutcomments.com/2008/09/21/when-is-multi-threading-not-a-good-idea/feed/</wfw:commentRss>
		</item>
		<item>
		<title>(Disappointing) Thoughts on CyberResearch "H" Series DIO Cards OR Reading and Writing with the HDIO ISO32LU</title>
		<link>http://www.codingwithoutcomments.com/2008/09/14/disappointing-thoughts-on-cyberresearch-h-series-dio-cards-or-reading-and-writing-with-the-hdio-iso32lu/</link>
		<comments>http://www.codingwithoutcomments.com/2008/09/14/disappointing-thoughts-on-cyberresearch-h-series-dio-cards-or-reading-and-writing-with-the-hdio-iso32lu/#comments</comments>
		<pubDate>Sun, 14 Sep 2008 22:32:09 +0000</pubDate>
		<dc:creator>codingwithoutcomments</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[CyberResearch]]></category>

		<category><![CDATA[DIO]]></category>

		<category><![CDATA[H-Series]]></category>

		<category><![CDATA[HDIO ISO32LU]]></category>

		<category><![CDATA[PCIDAQ 1210]]></category>

		<category><![CDATA[Rants]]></category>

		<category><![CDATA[Read]]></category>

		<category><![CDATA[Write]]></category>

		<guid isPermaLink="false">http://www.codingwithoutcomments.com/?p=304</guid>
		<description><![CDATA[The last few days I've been working with CyberResearch's HDIO ISO32LU Low Profile PCI Digital I/O Board.  My mission?  Easy.  Read and Write a few bits of DIO.  How hard can it be right?  I thought that because I was familiar with CyberResearch's PCIDAQ1210, getting up and going with the [...]]]></description>
			<content:encoded><![CDATA[<p>The last few days I've been working with <a href="http://www.cyberresearch.com/">CyberResearch</a>'s <a href="http://www.cyberresearch.com/store/data-acquisition-control/digital-io-digital-input-output-interface/HDIO_ISO32LU_5880.2.htm">HDIO ISO32LU Low Profile PCI Digital I/O Board</a>.  My mission?  Easy.  Read and Write a few bits of DIO.  How hard can it be right?  I thought that because I was familiar with CyberResearch's <a href="http://www.cyberresearch.com/store/data-acquisition-control/analog-input-boards-ad-cards/PCIDAQ_1210_2787.2.htm">PCIDAQ1210</a>, getting up and going with the HDIO would be easy.  I thought 30 minutes, max.  It's DIO.  How hard can it be?  Hard enough it seems.</p>
<h2>Bad Programming Examples</h2>
<p>The HDIO software provides you with a multitudinous number of programming examples.  Great, right?  Surely there’s a simple console programming example for reading and/or writing a single BIT to the card with the DIO card because I’m quite certain that 90% of people/companies using the card are ONLY going using it for simple reads and writes.  OK, let’s see.  Well, first we have to translate the cryptic programming example folder naming scheme.</p>
<p>DI_INT<br />
DI_PATTN<br />
DI_SOFT<br />
DI_SOFT-DWORD</p>
<p>Are they only given DOS machines to work with over at CyberResearch?  Come on guys, XP gives you 255 characters in which to name filenames and folders.  Let’s be a little more specific shall we?  With new technologies, the learning curves are already high enough.  Give us a break.</p>
<p>I finally figured out that DI is short for “DIO”.  INT is short for “interrupt”.  Pattn short for pattern.  Soft is short for…?  Software?  It’s a mystery.  Opening a few of these examples yields bloated ugly laberinthian MFC GUI code with a tiny bit of actual API calls to the DIO demonstating advanced card functionality that most people probably will never use.  Listen guys, I don’t care to look at your ugly GUI code ESPECIALLY if it hides the actual real functionaity of the code.   Give Me a Text Based Example.  You aren’t teaching us how to use MFC.  You are teaching us how to use the DIO card.</p>
<p>To add insult to injury, after running these examples, I had no idea what a single one of them were actually trying to do.</p>
<p>So I turned to “Driver.chm” document provided by the installed software (c:/ProgramFiles/CyberResearch/ADSAPI/Manual) which contains a list of all API commands.   In the document, I found that the command for reading a single BIT was “DRV_DioReadBit.”  I did a serach for this phrase in all the examples and yielded zero results.  There were no programming examples which showed me how to read a simple BIT from DIO.</p>
<p>(ASIDE:  Microsoft Help files (.chm) are gastly.  I don’t care if they are industry standard.  They are hard to navigate, difficult to search, and impossible to print out the entire thing.  Give me an Online API or a PDF please).</p>
<p>The irony is that CyberResearch actually provides a test program where you can simply toggle or read a single bit and view the results.  But for some reason, they don’t feel like it’s important enough to give you the code for <em>that</em> application.  Just another example of a  company not being in touch with their customer.</p>
<p><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2008/09/diotestprogram.bmp"><img class="alignnone size-medium wp-image-306" title="diotestprogram" src="http://www.codingwithoutcomments.com/wp-content/uploads/2008/09/diotestprogram.bmp" alt="Test Program Provided By CyberResearch" /></a></p>
<h2>Not the same API Commands (not even close)</h2>
<p>Another thing that perturbs me about the H-Series DIO API calls, is that the call to Read a Single BIT is nothing like PCIDAQ 1210’s API calls. Well, actually, they are <em>exactly</em> alike.  But you wouldn’t know it just by looking at the API.</p>
<p>The API call to Read a Bit on the <a href="http://www.cyberresearch.com/store/data-acquisition-control/digital-io-digital-input-output-interface/HDIO_ISO32LU_5880.2.htm">HDIO ISO32LU</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">FTYPE DRV_DioReadBit<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">LONG</span> DriverHandle, LPT_DioReadBit lpDioReadBit<span style="color: #008000;">&#41;</span>;</pre></div></div>

<p>The API call to Read a Bit on the PCIDAQ 1210:</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">I16 DI_ReadLine<span style="color: #008000;">&#40;</span>U16 CardNumber, U16 Port, U16 Line, U16 <span style="color: #000040;">*</span> state<span style="color: #008000;">&#41;</span>;</pre></div></div>

<p>To perform the exact same functionality, these two cards have two completely different function names.  These two functions also take different data types and have a few different variable names for the exact same information.  Let me show you how the two translate:</p>
<p>‘DriverHandle’ on the IDO32LU = ‘CardNumber’ on the DAQ</p>
<p>LPT_DioReadBit lpDioReadBit is a structure with the following elements:  Port, Bit and State.</p>
<p>Port = Port<br />
Line = Bit (confusing)<br />
State = State</p>
<p>How easy would it be to use a universal naming structure between API’s for different cards CyberResearch?</p>
<h1>Reading and Writing with the HDIO IDO32LU</h1>
<h2>Open a Device</h2>
<p>OK, enough of me ranting and raving about CyberResarch rediculousness.  I know why you are here.  You want to know how to simply Read and Write a single Bit.  The first thing you need to do if open the Device you intend to use.  A call to <strong>DRV_DeviceOpen</strong> returns a <strong>DriverHandle</strong> which will be used in the API calls to Read and Write a single BIT.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">LRESULT        ErrCde;
<span style="color: #0000ff;">char</span>          szErrMsg<span style="color: #008000;">&#91;</span><span style="color: #0000dd;">80</span><span style="color: #008000;">&#93;</span>;
<span style="color: #0000ff;">static</span> ULONG  dwDeviceNum;
<span style="color: #0000ff;">static</span> <span style="color: #0000ff;">LONG</span>   DriverHandle <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">LONG</span><span style="color: #008000;">&#41;</span><span style="color: #0000ff;">NULL</span>; 
&nbsp;
ErrCde <span style="color: #000080;">=</span> DRV_DeviceOpen<span style="color: #008000;">&#40;</span>dwDeviceNum, <span style="color: #008000;">&#40;</span><span style="color: #0000ff;">LONG</span> far <span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span><span style="color: #000040;">&amp;</span>DriverHandle<span style="color: #008000;">&#41;</span>;
<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>ErrCde <span style="color: #000040;">!</span><span style="color: #000080;">=</span> SUCCESS<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    DRV_GetErrorMessage<span style="color: #008000;">&#40;</span>ErrCde,<span style="color: #008000;">&#40;</span>LPSTR<span style="color: #008000;">&#41;</span>szErrMsg<span style="color: #008000;">&#41;</span>;
    <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> ErrCde <span style="color: #000080;">&lt;&lt;</span> endl; <span style="color: #0000ff;">return</span> <span style="color:#800080;">0</span>; <span style="color: #008000;">&#125;</span></pre></div></div>

<h2>Writing a Bit</h2>
<p>To write a single BIT to the DIO card, declare a new instance of the structure <strong>PT_DioWriteBi</strong> and define the port, bit, and state in that structure.  Then, just pass the address of the structure to the API call <strong>DRV_DioWriteBit</strong> along with the DriverHandle.  If case you are wondering about which port to use, Port 0 refers to IDO0 through IDO7 on the IDO32LU.  Port 1 refers to IDO8 through 15.  You can see the pin-outs on page 25 of the manual provided to you by CyberResearch.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;"> PT_DioWriteBit lpDIOWriteBit;
 lpDIOWriteBit.<span style="color: #007788;">port</span> <span style="color: #000080;">=</span> <span style="color:#800080;">0</span>;
 lpDIOWriteBit.<span style="color: #007788;">bit</span> <span style="color: #000080;">=</span> <span style="color:#800080;">0</span>;
 lpDIOWriteBit.<span style="color: #007788;">state</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">1</span>;
&nbsp;
 ErrCde <span style="color: #000080;">=</span> DRV_DioWriteBit<span style="color: #008000;">&#40;</span>DriverHandle, <span style="color: #008000;">&#40;</span>LPT_DioWriteBit<span style="color: #008000;">&#41;</span><span style="color: #000040;">&amp;</span>lpDIOWriteBit <span style="color: #008000;">&#41;</span>;
 <span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>ErrCde <span style="color: #000040;">!</span><span style="color: #000080;">=</span> SUCCESS<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
   DRV_GetErrorMessage<span style="color: #008000;">&#40;</span>ErrCde,<span style="color: #008000;">&#40;</span>LPSTR<span style="color: #008000;">&#41;</span>szErrMsg<span style="color: #008000;">&#41;</span>;
   <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> ErrCde <span style="color: #000080;">&lt;&lt;</span> endl; <span style="color: #0000ff;">return</span> <span style="color:#800080;">0</span>; <span style="color: #008000;">&#125;</span></pre></div></div>

<h2>Reading a Bit</h2>
<p>Reading is a little ticker.  In order to Read a BIT, you again provide a Driver Handle, but this time provide an address to a declared <strong>PT_DioReadBit</strong> structure.  The real tricky part?  Remembering to allocate memory of size USHORT that will hold the state information once it has been populated by the call to <strong>DRV_DIOReadBit.</strong> Below, rbvalue is declared of type USHORT, then this memory is pointed to by the state variable in the declared 'PT_DioReadBit' structure.  If you forget to allocate that memory, prepare for your program to crash.  If case you are wondering about which port to use, Port 0 refers to IDI0 through IDI7 on the IDO32LU.  Port 1 refers to IDI8 through IDI15.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">PT_DioReadBit lpDIOReadBit;
USHORT rbValue;
lpDIOReadBit.<span style="color: #007788;">port</span> <span style="color: #000080;">=</span> <span style="color:#800080;">0</span>;
lpDIOReadBit.<span style="color: #007788;">bit</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">5</span>;
lpDIOReadBit.<span style="color: #007788;">state</span> <span style="color: #000080;">=</span> <span style="color: #008000;">&#40;</span>USHORT far <span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span><span style="color: #000040;">&amp;</span>rbValue; 
&nbsp;
ErrCde <span style="color: #000080;">=</span> DRV_DioReadBit<span style="color: #008000;">&#40;</span> DriverHandle, <span style="color: #008000;">&#40;</span>LPT_DioReadBit<span style="color: #008000;">&#41;</span><span style="color: #000040;">&amp;</span>lpDIOReadBit <span style="color: #008000;">&#41;</span>;
<span style="color: #0000ff;">if</span> <span style="color: #008000;">&#40;</span>ErrCde <span style="color: #000040;">!</span><span style="color: #000080;">=</span> SUCCESS<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
   DRV_GetErrorMessage<span style="color: #008000;">&#40;</span>ErrCde,<span style="color: #008000;">&#40;</span>LPSTR<span style="color: #008000;">&#41;</span>szErrMsg<span style="color: #008000;">&#41;</span>;
   <span style="color: #0000dd;">cout</span> <span style="color: #000080;">&lt;&lt;</span> ErrCde <span style="color: #000080;">&lt;&lt;</span> endl; <span style="color: #0000ff;">return</span> <span style="color:#800080;">0</span>; <span style="color: #008000;">&#125;</span> 
&nbsp;
 USHORT state <span style="color: #000080;">=</span> <span style="color: #000040;">*</span>lpDIOReadBit.<span style="color: #007788;">state</span>;</pre></div></div>

<p>In my opinion, having to allocate your memory for the state variable is unnecessary complexity that could have been side-stepped by CyberResearch in the programming of the API for the IDO32LU.  Especially with the newest generation of programmers being so unfamilar with C, I find they could have been a wee bit more user friendly.</p>
<h1>In Conclusion</h1>
<p>I wrote this entry to save you a little bit of time.  It took me three hours to figure out how to read and write a bit to the DIO card.  Maybe I'm just dumb.  Or maybe, it was a little bit harder then it should of been.  I normally don't take the time to write scathing reviews of products, but I firmly believe that DIO is fundamental and should be one of the easiest tasks to complete.  I should be able to call a function called WriteBit(int Port, int Bit, int State) and it should write the BIT.  I should be able to call a function ReadBit(int Port, int Bit, int * state) and it should return the state.  It should be this easy.  These two functions would be printed on the front cover of my manual of the DIO card I'm trying to sell.  If not in the manual, they should be in simple text based console programming examples entitled 'Reading a Bit From the DIO' and 'Write a single BIT to the DIO.'  If not in an example, they should be in an online API or pdf.  Am I asking for too much?  I don't think so.   Get with the program CyberResearch.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codingwithoutcomments.com/2008/09/14/disappointing-thoughts-on-cyberresearch-h-series-dio-cards-or-reading-and-writing-with-the-hdio-iso32lu/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Windows Serial Programming - Tips and Tricks</title>
		<link>http://www.codingwithoutcomments.com/2008/09/10/tips-and-tricks-on-windows-serial-programming/</link>
		<comments>http://www.codingwithoutcomments.com/2008/09/10/tips-and-tricks-on-windows-serial-programming/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 02:43:12 +0000</pubDate>
		<dc:creator>codingwithoutcomments</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[C]]></category>

		<category><![CDATA[CommTimeouts]]></category>

		<category><![CDATA[ReadFile]]></category>

		<category><![CDATA[RS-232]]></category>

		<category><![CDATA[RS-422]]></category>

		<category><![CDATA[RS-485]]></category>

		<category><![CDATA[Serial]]></category>

		<category><![CDATA[Windows]]></category>

		<category><![CDATA[WriteFile]]></category>

		<guid isPermaLink="false">http://www.codingwithoutcomments.com/?p=274</guid>
		<description><![CDATA[The last couple days I have been working on Serial Communications (RS-422 and RS-485) between a Windows PC and an Embedded FPGA Processor.  From start to finish, synchronizing the data transfer between the two systems only took about half a day.  When I first started using serial communications a few years ago, it [...]]]></description>
			<content:encoded><![CDATA[<p>The last couple days I have been working on Serial Communications (RS-422 and RS-485) between a Windows PC and an Embedded FPGA Processor.  From start to finish, synchronizing the data transfer between the two systems only took about half a day.  When I first started using serial communications a few years ago, it took me a week to establish a good working link.  Between then and now, I've noticed a few tips and tricks along the way which has helped get communication between two devices up-to-speed more quickly.</p>
<h2>Not a Perpetual Motion Machine</h2>
<p>What makes serial a bit difficult to work with is that it is (in general) not plug-and-play.  The code used to communicate to one type of board, won't work straight-out-of-the-box with another type of board.  Like snowflakes, no two serial-com links are alike.  There is no perpetual motion machine.  Each has individual timing constraints and quirks.  Sometimes you can read about these timing constraints in the spec, but most times a good link is established only after a big battle of trial-and-error.  This also makes it hard to do serial comm research on the Internet.  Copying and pasting serial code from a website you find on google rarely works.  It can help you get the gist of what is going on, but unfortunately, prepare to put in some legwork.</p>
<h2>Know the baud-rate, parity, stop-bit, and byte-size</h2>
<p>This is essential.  Before even getting started make sure you know the baud-rate, parity, stop-bit, and byte-size information of the device you are trying to communicate to.  If you have this information wrong, you are pretty much dead in the water from the get-go.  Nothing will work.  Check and double check this information.  I don't know how many times I've ported serial code from one project to the other, ran it, then hit my head against a wall for a few hours before realizing that, duh, the last FPGA that I was communicating to was in 19200 the new FPGA is in 9600.  These variables should be the first to be modified when programming serial in the windows environment.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">DCB properties;
&nbsp;
GetCommState<span style="color: #008000;">&#40;</span>hCom, <span style="color: #000040;">&amp;</span>properties<span style="color: #008000;">&#41;</span>;
properties.<span style="color: #007788;">BaudRate</span> <span style="color: #000080;">=</span> CBR_19200;
properties.<span style="color: #007788;">Parity</span> <span style="color: #000080;">=</span> ODDPARITY;
properties.<span style="color: #007788;">StopBits</span> <span style="color: #000080;">=</span> ONESTOPBIT;
properties.<span style="color: #007788;">ByteSize</span> <span style="color: #000080;">=</span> <span style="color: #0000dd;">8</span>;
SetCommState<span style="color: #008000;">&#40;</span>hCom, <span style="color: #000040;">&amp;</span>properties<span style="color: #008000;">&#41;</span>;</pre></div></div>

<h2>Auto-Toggle or Manual?  Know your serial card.</h2>
<p>Oh Auto-Toggle. How we love thee.  Let me count the ways.  Auto-Toggle is a function that is built into certain serial cards that automatically toggles the transmit lines when bytes are sent then immediately toggles back to the recieve line to await bytes from the device to whom you were talking.  The problem is that most serial cards don't have Auto-Toggle and sometimes even when they have it doesn't operate properly.  Make sure you know to which camp you belong.  Know your serial card.  If your card has auto-toggle, verify that it works using an oscilloscope (we'll talk about that later).  If it doesn't, know that you have to manually toggle the transmit and receive lines.</p>
<p>Enabling RTS_CONTROL toggles the transmit line and allows the user to transmit data over serial.  When RTS_CONTROL has been enabled, the user cannot recieve any data over serial.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">GetCommState<span style="color: #008000;">&#40;</span>m_hCom, <span style="color: #000040;">&amp;</span>properties<span style="color: #008000;">&#41;</span>;
properties.<span style="color: #007788;">fRtsControl</span> <span style="color: #000080;">=</span> RTS_CONTROL_ENABLE;
SetCommState<span style="color: #008000;">&#40;</span>m_hCom, <span style="color: #000040;">&amp;</span>properties<span style="color: #008000;">&#41;</span>;</pre></div></div>

<p>Diabling RTS_Control toggles the recieve line and allows the user to recieve data over serial.  When RTS_CONTROL has been disabled, the user cannot send any data over serial.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">GetCommState<span style="color: #008000;">&#40;</span>m_hCom, <span style="color: #000040;">&amp;</span>properties<span style="color: #008000;">&#41;</span>;
properties.<span style="color: #007788;">fRtsControl</span> <span style="color: #000080;">=</span> RTS_CONTROL_DISABLE;
SetCommState<span style="color: #008000;">&#40;</span>m_hCom, <span style="color: #000040;">&amp;</span>properties<span style="color: #008000;">&#41;</span>;</pre></div></div>

<p>If you are working with RS-485, and auto-toggle isn't an option, manually controlling the transmit/recieve lines is very necessary as RS-485 is half-duplex (which means that the transmit/receive lines are shared).   If working with RS-422, which is full-duplex, transmit and receive are not being shared (both have separate lines) and toggling the transmit/receive lines should not be necessary.  However, just this week I was working with a RS-422 and communication would not work unless I still toggled transmit/receive - go figure.</p>
<h2>Give the WriteFile command time to breathe</h2>
<p>After transmitting bytes using the WriteFile command, proper time must be given after executing WriteFile and before RTS_CONTROL is disabled.  Unfortunately, the WriteFile command doesn't (properly) verify that all bytes are written to the transmit line.  If RTS_CONTROL is disabled too quickly after WriteFile, bytes can actually be chopped off the end of your message.  If you are losing bytes, simply insert something I like to call a 'for loop to nowhere' after the WriteFile command.  It just wastes a little time before you disable RTS_CONTROL and makes sure all bytes are transmitted.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">DCB properties;
&nbsp;
GetCommState<span style="color: #008000;">&#40;</span>m_hCom, <span style="color: #000040;">&amp;</span>properties<span style="color: #008000;">&#41;</span>;
properties.<span style="color: #007788;">fRtsControl</span> <span style="color: #000080;">=</span> RTS_CONTROL_ENABLE;
SetCommState<span style="color: #008000;">&#40;</span>m_hCom, <span style="color: #000040;">&amp;</span>properties<span style="color: #008000;">&#41;</span>;
&nbsp;
<span style="color: #0000ff;">BOOL</span> ok <span style="color: #000080;">=</span> <span style="color: #008080;">::</span><span style="color: #007788;">WriteFile</span><span style="color: #008000;">&#40;</span>m_hCom,<span style="color: #008000;">&#40;</span><span style="color: #0000ff;">void</span> <span style="color: #000040;">*</span><span style="color: #008000;">&#41;</span>buffer,bytes_to_send,<span style="color: #000040;">&amp;</span>bytesSent,<span style="color: #0000ff;">NULL</span><span style="color: #008000;">&#41;</span>;
&nbsp;
<span style="color: #0000ff;">for</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">int</span> i <span style="color: #000080;">=</span> <span style="color:#800080;">0</span>; i <span style="color: #000080;">&lt;</span> <span style="color: #0000dd;">200000</span>; i<span style="color: #000040;">++</span><span style="color: #008000;">&#41;</span>; <span style="color: #666666;">//waste a little time</span>
&nbsp;
GetCommState<span style="color: #008000;">&#40;</span>m_hCom, <span style="color: #000040;">&amp;</span>properties<span style="color: #008000;">&#41;</span>;
properties.<span style="color: #007788;">fRtsControl</span> <span style="color: #000080;">=</span> RTS_CONTROL_DISABLE;
SetCommState<span style="color: #008000;">&#40;</span>m_hCom, <span style="color: #000040;">&amp;</span>properties<span style="color: #008000;">&#41;</span>;</pre></div></div>

<h2>Use an Oscilloscope! ! !</h2>
<p>Before I go any further, I'd like to urge you, no, gently prod you to use what I consider the number one best way to get serial communications up and running: the Oscilloscope.  Using the Oscilloscope you can really nail down the timing of your sent and received messages over serial communications.  You can measure the time it takes to send and receive one byte.  You can measure the time between when the last byte is sent by the WriteFile command and when a response is seen on the receive line.   You can actually SEE (I spy with my little eye) that you are disabling the RTS_CONTROL line too early and thus cutting off bytes.  The Oscilloscope will save you time and thus head-banging hair-wrencing frustration.  I guarantee it. I recommend setting two trigger points if using RS-422.  One on the receive and one on the transmit line.</p>
<h2>Free Serial Port Monitor</h2>
<p>Another tool that I use constantly while working on Serial Programming is the <a href = "http://www.serial-port-monitor.com/">Free Serial Port Monitor.</a>  This program allows you to monitor a specific COM port and shows you exactly what you have <i>written</i> and what you have <i>read</i> on that COM port.  The tool is perfect when you are just getting started if you just want to know if you are writing anything at all.  Sometimes, if you aren't using an Oscilloscope, it is difficult to tell if any bytes are being written correctly.  Also, this tool shows you <b>exactly</b> how many bytes are being read and what bytes are being read with the ReadFile command.  This helps you debug your serial read calls because you can see if you are chopping your message in half with the ReadFile command and adjust accordingly.</p>
<h2>Reading when you know what to expect</h2>
<p>If you are working on a command and response based serial system, one in which you issue and command and expect back a response of a certain length &#8212; reading on serial is a cinch.  You just have to know three little bits (or should I say bytes?) of information.  The first is the maximum time interval between the characters you are receiving in milliseconds.  This can be found in your spec (if you are given a spec) or can be found with an Oscilloscope. The second is the number of bytes you expect back.  The third is the time it takes to send one character (this can be found with a simple math equation).  I'll tell you how to use this information below after I drop a big lump of code on you.</p>

<div class="wp_syntax"><div class="code"><pre class="cpp cpp" style="font-family:monospace;">DWORD Serial_Controller_Class<span style="color: #008080;">::</span><span style="color: #007788;">Receive_Message</span><span style="color: #008000;">&#40;</span><span style="color: #0000ff;">unsigned</span> <span style="color: #0000ff;">char</span> <span style="color: #000040;">*</span> Msg_Ptr,
<span style="color: #0000ff;">int</span> ExpectedNumberOfBytes, <span style="color: #0000ff;">int</span> MaxTimeBetweenChar, <span style="color: #0000ff;">int</span> MaxTimeToSendSingleChar<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> 
&nbsp;
    DWORD bytesRead <span style="color: #000080;">=</span> <span style="color:#800080;">0</span>;
&nbsp;
   COMMTIMEOUTS comTimeOut;
   comTimeOut.<span style="color: #007788;">ReadIntervalTimeout</span> <span style="color: #000080;">=</span> MaxTimeBetweenChar;
   comTimeOut.<span style="color: #007788;">ReadTotalTimeoutMultiplier</span> <span style="color: #000080;">=</span> ExpectedNumberOfBytes;
   comTimeOut.<span style="color: #007788;">ReadTotalTimeoutConstant</span> <span style="color: #000080;">=</span> MaxTimeToSendSingleChar;
   SetCommTimeouts<span style="color: #008000;">&#40;</span>m_hCom,<span style="color: #000040;">&amp;</span>comTimeOut<span style="color: #008000;">&#41;</span>; 
&nbsp;
   <span style="color: #0000ff;">BOOL</span> ok <span style="color: #000080;">=</span> <span style="color: #008080;">::</span><span style="color: #007788;">ReadFile</span><span style="color: #008000;">&#40;</span>m_hCom,Msg_Ptr, ExpectedNumberOfBytes,<span style="color: #000040;">&amp;</span>bytesRead,<span style="color: #0000ff;">NULL</span><span style="color: #008000;">&#41;</span>; 
&nbsp;
  FlushFileBuffers<span style="color: #008000;">&#40;</span>m_hCom<span style="color: #008000;">&#41;</span>;
  <span style="color: #0000ff;">return</span> bytesRead;
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>The Receive Message method above has four elements passed to it. The first, MsgPtr, is used to hold the message received. ExpectedNumberOfBytes contains the number of bytes you expect to be returned based on the message you sent out on serial. The variables MaxTimeBetweenChar and MaxTimeToSendSingleChar are, in my opinion, pretty self explanatory. This passed data then can be used to set things called "Comm Timeouts."  Comm Timeouts are used to control the amount of time that ReadFile will sit and wait for a message to be recieved.  This is called "blocking" in the biz which means that all other processes are esentially "blocked" until ReadFile has finished executing.  This is why setting CommTimeouts correctly are extreamly important.  We don't want to "block" for longer then necessary. Each Comm Timeout is explained in detail below.</p>
<blockquote><p>DWORD ReadIntervalTimeout - sets max period of time (in milliseconds) allowed between two sequential characters being read from the line of commutation. During the 'read' operation the time period countdown takes its start when the first character is received. When the interval between two sequential characters exceeds the given value the 'read' operation finishes and all the data accumulated in the buffer are transmitted to the programme. Zero value of this member indicates that this timeout isn't used.</p>
<p>DWORD ReadTotalTimeoutMultiplier- sets the multiplier (in milliseconds) used to calculate general timeout of the 'read' operation. In every case this value is multiplied by the quantity of the characters requested for reading.</p>
<p>DWORD ReadTotalTimeoutConstant - sets a constant (in milliseconds) used to calculate the general timeout of the operation. In case of every 'read' operation this value is added to the result of multiplying ReadTotalTimeoutMultiplier by the quantity of the characters requested for the reading. ReadTotalTimeoutMultiplier and ReadTotalTimeoutConstant mean that general timeout for 'read' operation isn't used.</p></blockquote>
<p>Here's how to calculate MaxTimeToSendSingleCharacter.  If we transfer one character at 19200 baud, 8 bits per byte, plus parity complement and one stop bit, then there will be 11 bits total per character.</p>
<p align="center"><strong>MaxTimeToSendSingleCharacter =  11x(1/19200) = .057 milliseconds (which can be rounded up to 1 milliscond).</strong></p>
<p>Imagine that we read 100 characters at a rate of 19200 bps. If 8 bits per character, parity complement and one stop bit are used, then there will be be 11 bits (including the start bit) per character in the physical line. So 100 characters at a rate 19200 bit/s will be received as</p>
<p align="center"><strong>100&#215;11x(1/19200)=0.0572916 sec</strong></p>
<p>or approximately 57.2 milliseconds. If there is no interval between receiving multiple characters.   If the interval between the characters is about a half time of one character transmission, i.e. 0.25 milliseconds, the reception time is calculated as</p>
<p align="center"><strong>100&#215;11x(1/19200)+(99&#215;0.00025)=0.00820416 sec</strong></p>
<p>or give or take 82 milliseconds. If the reading process has amounted to longer then 82 milliseconds, we can suppose there's been an external device error and stop the 'read' operation to anymore program blockage.  Phew.</p>
<p>"No More Math!  No More Math!"  I hear you chant.  Fear not, we are done.</p>
<h2>Reading when you have no idea</h2>
<p>When you have no idea how many bytes to expect back, the best thing to do is to follow the steps above with one exception.  Hopefully you know the maximum number of bytes that can be sent at any given time.  If you know that, just use that number for ExpectedNumberOfBytes.</p>
<h2>Thats it!</h2>
<p>These are my tricks.  OK, maybe they are really tricks.  Maybe they are just a better explanation of the dry-and-boring RS-232 specification that you've been starting at and scratching your head over for the past week or so.  Regardless, I hope some of these tidbits helped.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codingwithoutcomments.com/2008/09/10/tips-and-tricks-on-windows-serial-programming/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Project Euler - Problem 4 - Palindromes</title>
		<link>http://www.codingwithoutcomments.com/2008/09/09/project-euler-problem-4/</link>
		<comments>http://www.codingwithoutcomments.com/2008/09/09/project-euler-problem-4/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 02:12:53 +0000</pubDate>
		<dc:creator>codingwithoutcomments</dc:creator>
		
		<category><![CDATA[Project Euler]]></category>

		<category><![CDATA[Palindrome]]></category>

		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.codingwithoutcomments.com/?p=281</guid>
		<description><![CDATA[Project Euler “is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.”
I've been working through some of the projects on the website [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://projecteuler.net/"></a><a href="http://www.codingwithoutcomments.com/wp-content/uploads/2008/08/euler_main.jpg"><img class="alignleft size-medium wp-image-201" style="margin: 3px;" title="euler_main" src="http://www.codingwithoutcomments.com/wp-content/uploads/2008/08/euler_main-258x300.jpg" alt="" width="258" height="300" /></a>Project Euler “is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.”</p>
<p>I've been working through some of the projects on the website to help teach myself Ruby in my space time.</p>
<p>Problem 4 of Project Euler states the following:</p>
<blockquote><p><strong>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91  99.</p>
<p>Find the largest palindrome made from the product of two 3-digit numbers.</strong></p></blockquote>
<p>Just doing some simple calculations, the smallest number that can be generated by two 3 digits numbers multiplied together is:</p>
<p>100 * 100 = 10,000 which is a five digit number.  <br />
An example of a five digit palindrome is 10101</p>
<p>The largest number is:</p>
<p>999 x 999 = 998,001 which is a six digit numbers.<br />
An example of a six digit palindrome is 101101.</p>
<p>With this information in mind, the solution I came up with in Ruby is below.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Palendromes
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize
    <span style="color:#0066ff; font-weight:bold;">@Solutions</span> = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> FindPalendromes
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">for</span> x <span style="color:#9966CC; font-weight:bold;">in</span> 100..999
    <span style="color:#9966CC; font-weight:bold;">for</span> y <span style="color:#9966CC; font-weight:bold;">in</span> 100..999
&nbsp;
      a = x <span style="color:#006600; font-weight:bold;">*</span> y
      a = a.<span style="color:#9900CC;">to_s</span>
      <span style="color:#9966CC; font-weight:bold;">next</span> <span style="color:#9966CC; font-weight:bold;">if</span><span style="color:#006600; font-weight:bold;">&#40;</span>a.<span style="color:#9900CC;">length</span> <span style="color:#006600; font-weight:bold;">%</span> <span style="color:#006666;">2</span> != 0<span style="color:#006600; font-weight:bold;">&#41;</span>  
&nbsp;
      b = <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span>
      a.<span style="color:#9900CC;">scan</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/</span><span style="color:#006600; font-weight:bold;">&#91;</span>0<span style="color:#006600; font-weight:bold;">-</span><span style="color:#006666;">9</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">/</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> |z|
        b <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> z
      <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
     <span style="color:#0066ff; font-weight:bold;">@Solutions</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> a <span style="color:#9966CC; font-weight:bold;">if</span><span style="color:#006600; font-weight:bold;">&#40;</span>isPalendome?<span style="color:#006600; font-weight:bold;">&#40;</span>b<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span> 
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#0066ff; font-weight:bold;">@Solutions</span>.<span style="color:#9900CC;">sort</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> isPalendome?<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">array</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
  reversearray = <span style="color:#CC0066; font-weight:bold;">array</span>.<span style="color:#9900CC;">reverse</span>
  <span style="color:#9966CC; font-weight:bold;">for</span> x <span style="color:#9966CC; font-weight:bold;">in</span> 0..<span style="color:#CC0066; font-weight:bold;">array</span>.<span style="color:#9900CC;">length</span>
    <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span> <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#CC0066; font-weight:bold;">array</span><span style="color:#006600; font-weight:bold;">&#91;</span>x<span style="color:#006600; font-weight:bold;">&#93;</span> != reversearray<span style="color:#006600; font-weight:bold;">&#91;</span>x<span style="color:#006600; font-weight:bold;">&#93;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">true</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
a = Palendromes.<span style="color:#9900CC;">new</span>
solutions = a.<span style="color:#9900CC;">FindPalendromes</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> solutions</pre></div></div>

<p>Starting at the bottom, a is set equal to a new instance of class Palindromes which is initialized with a call to the new method which in turn calls the initialize method which declares a new array called 'Solutions' where all the possible palindromes will be stored.  To find the palindromes, the 'FindPalindromes' method is deployed.  </p>
<p>FindPalindromes creates two loops from 100 to 999 so that every product of two three digit combination of numbers will be checked.  Entering the double for loop, x and y are multiplied together and stored in 'a'.  'a' is converted to a string so it can be more easily manipulated and it's length is checked.  If a is a five digit number and not a six digit number, a is discarded because it is obviously not the 'largest palindrome.'  </p>
<p>Next, using Regular Expressions,  each individual number is extracted from a (which is one long string) and put in individual elements in an newly created array b.  </p>
<p>For example the following conversion is made if a is equal to the string  '123456.'</p>
<p>b = {1, 2, 3, 4, 5, 6} </p>
<p>This is done so that array functions can be used to check if the number is actually a palindrome.  </p>
<p>Next, b is sent to the method isPalindrome() which checks if the numbers contained in b are of a palindromic nature.  The isPalindrome() method is simple.  The method reverses b and stores the results in 'reversearray,' then, it loops through the length of the array comparing each element.  If an element doesn't match up, it returns false and nothing happens.  If however, every element matches, the isPalindrome method returns true and a is pushed into the Solutions array.</p>
<p>When the double for loop has exhausted every possible triple digit product combination, the solution array is sorted and returned to be printed to the screen.  </p>
<p>The answer is: 906609</p>
<p>My solution, while yielding the correct answer, is not the most elegant solution I discovered (not to my surprise as I am still learning the intricacies of the Ruby Programming language).  On the Project Euler forum, Olathe posted the following code:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">max = 0
100.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">999</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> |a|
  a.<span style="color:#9900CC;">upto</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">999</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> |b|
    prod = a <span style="color:#006600; font-weight:bold;">*</span> b
    max = <span style="color:#006600; font-weight:bold;">&#91;</span>max, prod<span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">max</span> <span style="color:#9966CC; font-weight:bold;">if</span> prod.<span style="color:#9900CC;">to_s</span> == prod.<span style="color:#9900CC;">to_s</span>.<span style="color:#9900CC;">reverse</span>
  <span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;Maximum palindrome is #{ max }.&quot;</span></pre></div></div>

<p>This code is sick (in a good way).  He creates two for loops, finds the product of two three digit numbers, and converts the answer to a string &#8212; which is what I did in my code, but this is where the similarities end.  Instead of extracting single digits into an array, he simply compares the product string to a reversed product string.  If they match (if the number is a palindrome), he compares the number to the previous maximum number stored in the 'max' variable.  If bigger then the previous max, he stores the number in match.  If less, he discards it.  Yes.  Very Nice.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.codingwithoutcomments.com/2008/09/09/project-euler-problem-4/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 1.906 seconds -->
