<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>I'm pretty sure that's what I mean</title>
	<atom:link href="http://whatimean.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://whatimean.wordpress.com</link>
	<description>Mostly work-related technical ramblings</description>
	<lastBuildDate>Fri, 09 Dec 2011 15:48:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='whatimean.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>I'm pretty sure that's what I mean</title>
		<link>http://whatimean.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://whatimean.wordpress.com/osd.xml" title="I&#039;m pretty sure that&#039;s what I mean" />
	<atom:link rel='hub' href='http://whatimean.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Playing With Python</title>
		<link>http://whatimean.wordpress.com/2011/03/15/playing-with-python/</link>
		<comments>http://whatimean.wordpress.com/2011/03/15/playing-with-python/#comments</comments>
		<pubDate>Tue, 15 Mar 2011 15:41:25 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=181</guid>
		<description><![CDATA[What? This is just a quick post documenting my recent forays into Python programming and the kinds of things I managed to (quickly) do with it. You might ask &#8220;Why?&#8221;, well aside from the fact that learning new languages is fun and can keep you on your development toes, I&#8217;m seeing a lot of job [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=181&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>What?</h2>
<p>This is just a quick post documenting my recent forays into Python programming and the kinds of things I managed to (quickly) do with it.  You might ask &#8220;Why?&#8221;, well aside from the fact that learning new languages is fun and can keep you on your development toes, I&#8217;m seeing a lot of job adverts asking for skill sets which include scripting languages such as Ruby and Python.  Since I&#8217;ve done a spot of Ruby in the past, I figured why not spend some time messing around with Python.</p>
<h2>Do What?</h2>
<p>This is the problem to solve.  Given a triangle of numbers, find the shortest path from the top of the triangle to the bottom.  So consider the triangle;</p>
<p><code>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;9<br />
&nbsp;&nbsp;&nbsp;&nbsp;8  &nbsp;5<br />
&nbsp;&nbsp;5 &nbsp;10  &nbsp;7<br />
13  &nbsp;4  &nbsp;12  11</code></p>
<p>Moving between rows can only be done by going to the &#8216;root&#8217; of any particular number.  (Here, &#8220;root&#8221; in relation to trees not Maths).  So, if we were are number 10 in the second to last row, our only options of moving to the final row are to select 4 or 12.</p>
<p>For this triangle, the shortest path is &#8220;9, 8, 5, 4&#8243; which has a total weight of 26.</p>
<p>Starting from the top of the triangle will lead to a lot of messy backtracking, which, although doable, is a bit more complex than I want it to be.  Another top-down solution might be to start lots of threads and start them exploring the triangle[1].  Again, this is a potential solution, but there is a much simpler approach we could take.</p>
<p>Starting at the bottom of the triangle, we can easily work out the cheapest way to get from <em>row-1</em> to <em>row</em>.  With that data, we can move up the triangle, working out the cheapest way to get from the row below, to the current row until we get up to the top, in which case we would have calculated the shortest path.</p>
<p>Because we care about the path and not just it&#8217;s weight, I created a class to represent both the path and the weight.</p>
<h3>Classes</h3>
<p><code>class Path:<br />
&nbsp;&nbsp;def __init__(self,v):<br />
&nbsp;&nbsp;&nbsp;&nbsp;if isinstance(v,int):<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.path = [v]<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.weight = v<br />
&nbsp;&nbsp;&nbsp;&nbsp;else:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.path = list(v.path)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;self.weight = v.weight</p>
<p>&nbsp;&nbsp;def append(self, num):<br />
&nbsp;&nbsp;&nbsp;&nbsp;self.path.append(num)<br />
&nbsp;&nbsp;&nbsp;&nbsp;self.weight += num</p>
<p>&nbsp;&nbsp;def weight(self):<br />
&nbsp;&nbsp;&nbsp;&nbsp;return self.weight</p>
<p>&nbsp;&nbsp;def __repr__(self):<br />
&nbsp;&nbsp;&nbsp;&nbsp;str_list = ['Path:',`self.weight`,'\t',`self.path`]<br />
&nbsp;&nbsp;&nbsp;&nbsp;return ''.join(str_list)<br />
</code></p>
<p>The only interesting part of the code above, I think, is the use of &#8216;isinstance&#8217; to provide a form of constructor overloading.</p>
<h3>Accepting the input</h3>
<p>Accepting command line input from Python was also very easy, as it is in most scripting languages.</p>
<p><code>def readInput():<br />
&nbsp;&nbsp;triangle = []</p>
<p>&nbsp;&nbsp;while True:<br />
&nbsp;&nbsp;&nbsp;&nbsp;l = raw_input()<br />
&nbsp;&nbsp;&nbsp;&nbsp;if l == 'EOF':<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break<br />
&nbsp;&nbsp;&nbsp;&nbsp;else:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;row = buildRow(l);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;triangle.append(row)</p>
<p>&nbsp;&nbsp;return triangle</p>
<p>def buildRow(line):<br />
&nbsp;&nbsp;numRow = []<br />
&nbsp;&nbsp;strRow = line.rsplit(' ')<br />
&nbsp;&nbsp;for s in strRow:<br />
&nbsp;&nbsp;&nbsp;&nbsp;numRow.append(int(s))<br />
&nbsp;&nbsp;return numRow</code></p>
<p>This code accepts the input from the command line and returns us our triangle represented as a list of lists.  Using the same example as above, we get the list;</p>
<p><code>[[9], [8, 5], [5, 10, 7], [13, 4, 12, 11]]</code></p>
<p>Note, that I didn&#8217;t bother with any checking or validating that the input formed a correct triangle.</p>
<p>Then I needed a method to be able to convert a <em>[int]</em> to a <em>[Path]</em>.  As I was beginning to expect, this was going to be a simple matter.</p>
<p><code>def convertToPaths(row):<br />
&nbsp;&nbsp;paths = []<br />
&nbsp;&nbsp;for n in row:<br />
&nbsp;&nbsp;&nbsp;&nbsp;paths.append(Path(n))<br />
&nbsp;&nbsp;return paths</code></p>
<p>Being able to return tuples is also a very nice feature in Python and one I miss in Java after having spent time writing Haskell.  I used this feature when working out the parents of a particular number in the triangle.  In Java, I&#8217;d be forced to either create a &#8220;Parents&#8221; class which contained two numbers or return some kind of array or Collection which introduces a lot of places for errors and misuse.  Tuples here keep things very plain and simple.</p>
<p><code>def parents(cIndex, row):<br />
&nbsp;&nbsp;left = row[cIndex]<br />
&nbsp;&nbsp;right = row[cIndex+1]<br />
&nbsp;&nbsp;return (left,right)</code></p>
<p>I&#8217;m now ready for the algorithm proper.  Converting the bottom row of the triangle in a <em>[Path]</em> gives me a starting point.  Looking at the row above, I can calculate the cheapest way to get to it, knowing the current Path back to the bottom.  </p>
<p>Put another way, I take the bottom two rows of the table (one which is a <em>[Path]</em> and the one above which is a <em>[int]</em>) and merge them together to make a new row, of type <em>[Path]</em> but which is of the same length as the <em>[int]</em> row.  I repeat this process until there is only one row left, which should have only one element in it; a Path.</p>
<p>Here&#8217;s the code.</p>
<p><code>def calcPaths(base, row):<br />
&nbsp;&nbsp;newBase = []<br />
&nbsp;&nbsp;for i in range(0, len(row)):<br />
&nbsp;&nbsp;&nbsp;&nbsp;(l,r) = parents(i, base)<br />
&nbsp;&nbsp;&nbsp;&nbsp;if l.weight &lt; r.weight:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new = Path(l)<br />
&nbsp;&nbsp;&nbsp;&nbsp;else:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new = Path(r)<br />
&nbsp;&nbsp;&nbsp;&nbsp;new.append(row[i])<br />
&nbsp;&nbsp;&nbsp;&nbsp;newBase.append(new)<br />
&nbsp;&nbsp;return newBase</p>
<p>def calcShortestPath(triangle):<br />
&nbsp;&nbsp;row = len(triangle)-1<br />
&nbsp;&nbsp;base = convertToPaths(triangle[len(triangle)-1])<br />
&nbsp;&nbsp;while len(base) != 1:<br />
&nbsp;&nbsp;&nbsp;&nbsp;base = calcPaths(base, triangle[row-1])<br />
&nbsp;&nbsp;&nbsp;&nbsp;row -= 1<br />
&nbsp;&nbsp;return base.pop(0)</p>
<p>triangle = readInput()<br />
shortestPath = calcShortestPath(triangle)<br />
print shortestPath</code></p>
<h2>Then What?</h2>
<p>The algorithm I chose, merging one row of the triangle into the row above, looks very much like a fold.  (I can&#8217;t express who pleased with myself I was when such a functional solution magically popped into my brain when thinking about this problem).  I couldn&#8217;t find a fold function in Python, luckily, writing my own was very simple.</p>
<p><code>def foldl(f, a, l):<br />
&nbsp;&nbsp;if 0 == len(l):<br />
&nbsp;&nbsp;&nbsp;&nbsp;return a<br />
&nbsp;&nbsp;else:<br />
&nbsp;&nbsp;&nbsp;&nbsp;head = l.pop(0)<br />
&nbsp;&nbsp;&nbsp;&nbsp;a = f(a,head)<br />
&nbsp;&nbsp;&nbsp;&nbsp;return foldl(f,a,l)</code></p>
<p>As you can see this is a left fold.  This is not intended to be introduction into folds, but basically it works by accepting as arguments a function, an accumulator and a list.  It then applies the function to the accumulator and the head of the list.  It then recursively calls itself with the same function, the updated accumulator and the rest of the list until the list is empty.</p>
<p>So my main method now a bit more simple, with it&#8217;s intention more simply expressed by use of the fold method.</p>
<p><code>triangle.reverse()</p>
<p>def merge(paths, roots):<br />
&nbsp;&nbsp;if 0 == len(paths):<br />
&nbsp;&nbsp;&nbsp;&nbsp;return convertToPaths(roots)<br />
&nbsp;&nbsp;else:<br />
&nbsp;&nbsp;&nbsp;&nbsp;return calcPaths(paths,roots)</p>
<p>shortestPath = foldl(merge,[],triangle)<br />
print shortestPath[0]<br />
</code></p>
<p>Although finding the shortest path is now expressed a bit more elegantly.  We have to reverse the triangle.  This is because we received the input in such a way as the &#8216;base&#8217; of the triangle is the last element of the list, but we need to processes the bottom of the triangle first.</p>
<h2>So What?</h2>
<p>The thing that surprised me the most about programming Python was how easy it was.  And it was <em>really</em> easy.  The language syntax is simple and followed the same rules as most of the other languages I&#8217;ve picked up.</p>
<p>I particularly likes the way that everything, including functions, are objects and so can be passed around as arguments.  I first encountered passing functions as parameters in Haskell, and since picking up that trick have often been frustrated that Java hasn&#8217;t offered me a simple way of doing the same thing.</p>
<p>The only thing that put me off was the convoluted way of &#8220;overloading&#8221; a constructor.  Due to the way Python handles it&#8217;s types, overloading as we understand it in Java wasn&#8217;t possible.  I think that&#8217;s a pretty small price to pay for the simplicity and power that Python programming provides.</p>
<p>[1] I&#8217;ve taken this problem from an tech test for an interview I had recently which I <em>failed</em>.  The reason being that I&#8217;d spent many weeks prior to this particular interview reading about multi-threading at the new concurrency packages available in Java 5/6.  Whilst all that is great and important, because I&#8217;d become so immersed in that kind of programming, I forgot to look for the simple solution first.  My bad.  I guess when you spend a long time studying hammers, new problems instantly present themselves as nails.  There&#8217;s a lesson I won&#8217;t be forgetting in a hurry.  Interestingly, my multi-threaded approach just wasn&#8217;t per formant enough for large triangles (more than 60 rows) because it found more and more work to do the longer the algorithm ran.  With the above approach, the algorithm actually gets <em>less</em> work to do the closer it comes to a solution.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whatimean.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whatimean.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whatimean.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whatimean.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/181/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/181/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/181/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=181&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2011/03/15/playing-with-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>Simple Cell Automata in Haskell</title>
		<link>http://whatimean.wordpress.com/2010/10/19/simple-cell-automata-in-haskell/</link>
		<comments>http://whatimean.wordpress.com/2010/10/19/simple-cell-automata-in-haskell/#comments</comments>
		<pubDate>Tue, 19 Oct 2010 14:32:20 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[cell automata]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=169</guid>
		<description><![CDATA[Introduction To further help me improve my Haskell skills I&#8217;ve started writing an implementation of Conways Game of Live. The rules here are simple; The cells are laid out in a grid &#8211; my implementation assumes a square If any cell is &#8220;alive&#8221; and it has more than three neighbours, then the cell dies If [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=169&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>To further help me improve my Haskell skills I&#8217;ve started writing an implementation of <a href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">Conways Game of Live</a>.  The rules here are simple;</p>
<ul>
<li>The cells are laid out in a grid &#8211; my implementation assumes a square</li>
<li>If any cell is &#8220;alive&#8221; and it has more than three neighbours, then the cell dies</li>
<li>If any cell is &#8220;alive&#8221; and it has fewer than two neighbours, then the cell dies</li>
<li>If any cell is not alive and it has between two and three neighbours, then it comes to life</li>
</ul>
<p>I also wanted my cell automata to be nicely visible so I decided to use <a href="http://glade.gnome.org/">Glade</a> and <a href="http://www.haskell.org/gtk2hs/">Gtk2Hs</a> to make a nice GUI for it.</p>
<h3>Getting Everything Installed</h3>
<p>I already had GHC installed, so all I need to install was everything else.  Firstly, use the package manager to install Glade.  This was easy, the rest is easy to but involves using cabal.</p>
<p><code><br />
cabal install alex<br />
cabal install gtk2hs-buildtools<br />
cabal install gtk<br />
cabal install glade<br />
</code></p>
<p>To use your Glade/GTK stuff with GHC you need to use this incantation;</p>
<p><code><br />
ghc -package gtk --make MyProgram<br />
</code></p>
<p>Also, when using Glade the project file format needs to be changed from &#8220;GtkBuilder&#8221; to &#8220;Libglade&#8221;.</p>
<h3>The Code</h3>
<p>My code can be found in BitBucket here; <a href="https://bitbucket.org/tomhobbs/cellautomata">Cell Automata</a></p>
<p>The cell automata algorithm works okay see the &#8220;evolve&#8221; method.  I&#8217;m currently stalled on trying to make it work nicely in the GUI.  </p>
<p>I got stuck when trying to calculate the square root of an integer (and receive a rounded/truncated integer as the result).  I couldn&#8217;t make that work so I borrowed/stole some code from <a href="http://haskellsolutions.blogspot.com/2009/02/integer-square-root-of-positive-integer.htm">http://haskellsolutions.blogspot.com/2009/02/integer-square-root-of-positive-integer.htm</a> to work that bit out for me.  I couldn&#8217;t make the Haskell <font face="courier">sqrt</font> work properly.</p>
<p><em>Edit: I got this fixed.  To get an integer square root of an integer, the following incantation is used</em><br />
<code><br />
floor (sqrt (fromIntegral (length xs)))<br />
</code><br />
<em>In the above, <font face="courier">xs</font> is the list containing my cells world.  This is safe to do because in my implementation the size of the world is always a square number.  I&#8217;ve yet to run hlint over my code to check that it is sensible.  Edit ends.</em></p>
<p>If anyone can offer any insights into how to create a kind of animation thread (for want of a better phrase) to handle the rendering the evolution of the world I&#8217;d be very grateful!</p>
<p>Comments always welcome.</p>
<p><em>Edit: I finally got it all working, including a UI in HOpenGL.  The biggest problem I&#8217;m facing now is that there GOL algorithm is very ineffecient for large world sizes, I&#8217;m guessing this is because it does a lot of list traversals per cell.</em></p>
<p><em>I should also mention the following three sites which proved to be invaluable.</em></p>
<ol>
<li><a href="http://blog.mikael.johanssons.org/archive/2006/09/opengl-programming-in-haskell-a-tutorial-part-2/">Michi&#8217;s blog</a> which I &#8220;borrowed&#8221; the majority of the OpenGL code and module layout from</li>
<li><a href="http://www.cin.ufpe.br/~haskell/hopengl/ioref.html">Andre W B Furtado tutorial</a> for the IORef help</li>
<li><a href="http://myawesomeblag.blogspot.com/2007/03/opengl-tetris-in-haskell.html">My Awesome Blag</a> &#8211; which appears to be the only place on the Internet which shows how to use the timer callback</li>
</ol>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whatimean.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whatimean.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whatimean.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whatimean.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/169/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/169/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/169/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=169&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2010/10/19/simple-cell-automata-in-haskell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>Safety is not the same thing as patronizing</title>
		<link>http://whatimean.wordpress.com/2010/08/17/safety-is-not-the-same-thing-as-patronizing/</link>
		<comments>http://whatimean.wordpress.com/2010/08/17/safety-is-not-the-same-thing-as-patronizing/#comments</comments>
		<pubDate>Tue, 17 Aug 2010 21:02:49 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[best practise]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[quality]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=97</guid>
		<description><![CDATA[I hate cars and the lawmakers who govern their use. Speed limits hinder my progress; if I think it&#8217;s safe to do 100mph along some road, I should be allowed to. Seat belts, urgh! Don&#8217;t get me started on how uncomfortable and restrictive they are. I think it&#8217;s patronizing for car makers to fit new [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=97&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I hate cars and the lawmakers who govern their use.  Speed limits hinder my progress; if I think it&#8217;s safe to do 100mph along some road, I should be allowed to.  Seat belts, urgh!  Don&#8217;t get me started on how uncomfortable and restrictive they are.  I think it&#8217;s patronizing for car makers to fit new cars with airbags.  What kind of moron is going to drive into something that will necessitate an air bag?  Like the rest of the population, I consider myself an above average driver.  So I can get out of difficult situations without crashing, I can make fast progress safely and avoid all the obstacles.  Also, the car manufactures restrict the type of fuel I can put in the car.  Obviously, they don&#8217;t realise that sometimes one kind of fuel is cheaper than the other.  Who are they to dictate to me what kind of fuel I should use?</p>
<h2>Except that..</h2>
<p>&#8230;I can&#8217;t avoid all crashes.  Sure, more times than not, I&#8217;m a perfectly safe driver, regardless of what speed I&#8217;m doing or the road conditions or other situations.  But there are two very good reasons why I need all those safety features.</p>
<ol>
<li>Sometimes, I&#8217;m an idiot</li>
<li>Everyone else is also sometimes an idiot</li>
</ol>
<p>This little rant is in response to a couple of articles that have been bugging me recently.  Namely; <a href="http://blog.objectmentor.com/articles/2009/07/13/ending-the-era-of-patronizing-language-design">Patronizing Language Design</a>  and <a href="http://steve-yegge.blogspot.com/2010/07/wikileaks-to-leak-5000-open-source-java.html">Steve Yegge&#8217;s Java/Wikileaks article</a>.</p>
<p>Now, I don&#8217;t know either of those other authors.  The only thing I know about them is that they are both probably way more clever than me.  They&#8217;ve probably forgotten more great stuff than I&#8217;ll ever know.  Steve Yegge&#8217;s article in particular seems like it&#8217;s written as a comedy piece, but like all good comedy there&#8217;s a degree of truth hidden inside it.  I&#8217;ve not had a sense of humor amputation, I laughed and smiled about it as much as the next programmer.  However I do take issue the two premises that appear in these articles.</p>
<ol>
<li>Programming languages should allow any programmer to do whatever they want, and it&#8217;s the programmers responsibility to be safe</li>
<li>Object Orientated design, particularly in Java, forces developers to only use certain software components in known ways and that&#8217;s a restrictive and bad thing</li>
</ol>
<h2>Patronizing Programming Languages</h2>
<p>Preventing programmers from doing &#8216;more complicated&#8217; things is just a kind of seat belt.  Or maybe a better analogy is that of a speed-limiter as fitted to most trucks and vans these days.  (At least, in the UK.)  Think back to all the programmers you&#8217;ve ever worked with, all the <a href="http://www.thedailywtf.com">WTF</a> articles you&#8217;ve read.  Aren&#8217;t you kind of glad that some of those developers weren&#8217;t driving a lot faster when they crashed?  Particularly if it was <em>you</em> they crashed into!</p>
<p>The first article claims that even with more difficult language features available, an increase in program crashes has not been seen.  I don&#8217;t have access to his data so I can&#8217;t verify that claim.  My gut tells me though that this just can&#8217;t be the case.  If you took all the programs written in so-called &#8216;safe&#8217; languages and rewrote them in &#8216;un-safe&#8217; ones, I&#8217;m convinced that you&#8217;d see an increase in the number of nasty crashes.  </p>
<p>I&#8217;d be interested to visit an alternative reality and see what some of the enormous Java software projects that l&#8217;ve worked on look like when written in some less &#8216;patronizing&#8217; language.</p>
<p>The phrase &#8220;enough rope to hang yourself with&#8221; comes to mind.  Sure, you can hang yourself in &#8216;safe&#8217; languages such as Java, C# etc.  But that&#8217;s about it.  Introduce language features that give you even more rope and you could probably tie up and hang the entire town.  Neither outlook is pretty, but the differences in scale can&#8217;t be ignored.  Obviously, I&#8217;m not saying that this always going to happen, but I would argue that the occurrences of it happening would be greater &#8211; and messier.</p>
<h2>Doing Whatever You Want To Do</h2>
<p>I think that&#8217;s it&#8217;s fair to say that most of us write programs that are difficult or impossible (at least, according to our individual skill sets) to formally reason about.  This means that testing the behaviour of our software is limited to testing it in way we <em>think</em> that it&#8217;s going to be used &#8211; with some additional edge/exception cases thrown in for good measure.</p>
<p>In my opinion, the gripe about Java programs hiding implementation with <code>final</code> and non-public modifiers is more a gripe about Object Orientated design than about Java specifically.  (And goodness knows, I&#8217;ve moaned about Java enough!)  I just can&#8217;t get away from the fact that it is appropriate for some software components to be hidden away; other people may well want to use them in ways that they were not intended.</p>
<p>Ideally, any given class can be extended and have it&#8217;s non-private members overridden with predictable results.  Hopefully, such things are tested or at least well enough documented to allow other developers to not break anything else.  Opening up everything inside every class places an enormous burden of testing on the original developer; how can they possibly verify that if any of the internal code changes (because it has been overwritten) that the rest of the code will behave in the same expected manor.</p>
<p>You just have to ready any &#8220;How/Why Do I Do OO?&#8221; book or article to see why we encapsulate and hide data/functionality.  If you really <em>really</em> need some functionality which is private or final then the correct solution is to petition the vendor and ask for an API change.  (Good luck with that!)  To me, the Java/Wikileaks article should be more targeted at bad API design and less about abolishing final/private in any particular language.</p>
<p>Programming is not just about design-test-code, whatever language or silver bullet you&#8217;re using right now.  It&#8217;s also about support.  Making every possibly software component open to use (and abuse) is just asking for a support nightmare.  I would hazard a guess that the response to most support tickets would be closed with phrases like &#8220;Your computer caught fire because you overrode this method and you didn&#8217;t do something which the original method did&#8221; or &#8220;You lost £1,000,000 in business because you used that method which is not designed to be used in such a way&#8221;.</p>
<p>My car manufacturer says I should only put diesel in my particular car.  They&#8217;ve left the choice on whether or not I keep that restriction up to me, although it has to be said that they have not documented the repercussions of disobeying them very well in the car handbook.  I&#8217;m also not holding my breathe for any free support or fix if I do disregard their rules.  Now obviously, as a sensible person, I wouldn&#8217;t put unleaded, water, Lucozade or anything else in my fuel tank, but there is nothing physically stopping me.  But what happens one day when I&#8217;m day-dreaming whilst filling up and accidentally pick up the wrong pump?  After I&#8217;ve paid the expensive bill to get my car fixed, I bet that I wished that there was some physical restriction stopping me from doing the wrong thing.  <em>Even though I&#8217;d never made that kind of mistake before!</em></p>
<p>Remind me again why physical restrictions against accidental (or idiotic) mistakes are a bad thing.  Remind me again why an API designer hiding certain things from my code is a bad idea.</p>
<h2>Summary</h2>
<p>You might currently work only with brilliant people, but remember that not everyone does.  Every few months (or weeks) a new article is released about how education and training in this country or that is going down the tubes.  The bar to entry of the Programming Profession is already pretty low and seems to be getting lower.  Keeping &#8216;difficult&#8217; things away from the majority of those programmers, to me, seems like a good idea.<sub>1</sub>  I don&#8217;t let my kids play with sharp knives, but as they grow and move onto different meals (i.e. programming projects) different sets of cutlery (i.e. tools, languages, language features) will be introduced and they&#8217;ll be taught to use them.  But only if I consider their aptitude sufficient enough to wield them safely.  Even though some companies have very stringent hiring and interview practices, bad programmers still get jobs!</p>
<p>Programmers should lock their APIs down to a handful of known places which makes sense.  Then they can predicate what their users are going to do and help them do that.  Some programmers are going to complain that because of those restrictions they can&#8217;t do this or that with your API.  That complaining is okay.  Making everything open is just asking from trouble.  Not from you, the reader, obviously.  You&#8217;re an above-average programmer who doesn&#8217;t make mistakes.  But restrictive APIs are designed to protect software against programmers like me; you know, the human ones who do make mistakes.</p>
<p><sub>1</sub> Either that, or raise the bar to entry a bit more!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whatimean.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whatimean.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whatimean.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whatimean.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/97/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/97/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/97/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=97&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2010/08/17/safety-is-not-the-same-thing-as-patronizing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>Finding All the Paths In a Graph With Haskell</title>
		<link>http://whatimean.wordpress.com/2009/10/21/finding-all-the-paths-in-a-graph-with-haskell/</link>
		<comments>http://whatimean.wordpress.com/2009/10/21/finding-all-the-paths-in-a-graph-with-haskell/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 17:22:58 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[graph theory]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=108</guid>
		<description><![CDATA[Here&#8217;s an interesting problem&#8230; Given an undirected graph, find all the paths (not just the shortest) between two nodes that are less than some given length. I decided to attack this problem using Haskell. Simply because I&#8217;ve been trying to get to grips with the language and felt that this was a nice &#8220;real&#8221; problem [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=108&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Here&#8217;s an interesting problem&#8230;</h3>
<p>
Given an undirected graph, find <em>all</em> the paths (not just the shortest) between two nodes that are less than some given length.
</p>
<p>
I decided to attack this problem using Haskell.  Simply because I&#8217;ve been trying to get to grips with the language and felt that this was a nice &#8220;real&#8221; problem for me to practice my fledgling skills on.  I&#8217;ve chosen to model a graph as a list of edges which are described as a simple pair (see the end of the following source code).  I have therefore made the following assumptions in the code;
</p>
<ul>
<li>An entry in the list <font face="courier">(&#8216;a&#8217;,'b&#8217;)</font> explicitly states that an edge exists between the nodes &#8216;a&#8217; and &#8216;b&#8217; and further this implies that the edge <font face="courier">(&#8216;b&#8217;,'a&#8217;)</font> exists since the graph is undirected.</li>
<li>An entry <font face="courier">(&#8216;a&#8217;,'a&#8217;)</font> implies that a node &#8216;a&#8217; exists that does not have any edges, rather than an edge exists that self-references the node &#8216;a&#8217;.  Nodes are not allowed to have edges to themselves.</li>
</ul>
<p>
The following code does work, and returns the correct number of paths given my test data and the requests I make of it.  I can&#8217;t escape the feeling, though, that my Haskell could be made more simple and efficient.  I just don&#8217;t know Haskell well enough yet to work out how!
</p>
<h3>The Solution</h3>
<p><em>Edit 1:  code to apply Hlint comments</p>
<ul>
<li>Only HLint error: use of &#8220;not (elem &#8230;)&#8221; rather than &#8220;notElem &#8230;&#8221; has been fixed</li>
<li>HLint warning: use of &#8220;[p] ++ (some list)&#8221; rather than &#8220;p : (some list&#8221; has been fixed</li>
<li>HLint warning: unnecessary parenthesis used in a few places, most of these have been fixed</li>
</ul>
<p></em></p>
<p><em>Edit 2: corrected some cut and paste mistakes</em></p>
<p><code><br />
import Data.List</p>
<p>-- finds all the paths with length &lt;= l from u to v in g<br />
findAllPathsTo l u v g<br />
&nbsp;&nbsp;&nbsp;&nbsp;= filter endsAt (findAllPaths l u g)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;endsAt ps = (last ps) == v</p>
<p>-- finds all the paths with length  &gt;= l from u in g<br />
findAllPaths l n g<br />
&nbsp;&nbsp;&nbsp;&nbsp;| notElem n (allNodes g) = []<br />
&nbsp;&nbsp;&nbsp;&nbsp;| otherwise&nbsp;&nbsp;= allPaths' l g [[n]]</p>
<p>-------------------------------------------------------------------------------<br />
-- Supporting functions below<br />
-------------------------------------------------------------------------------</p>
<p>appendNeighboursToPath l p g<br />
&nbsp;&nbsp;&nbsp;&nbsp;= append ns p<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ns = neighbours n g<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;n = last p<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;append [] _  = []<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;append (n:ns) p = flatten (appendToAll l [p] n) : append ns p</p>
<p>neighbours a g<br />
&nbsp;&nbsp;&nbsp;&nbsp;= reverse (foldl step [] g)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where step acc (u,v)<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| u == a&nbsp;&nbsp;&nbsp;&nbsp;= v : acc<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| v == a&nbsp;&nbsp;&nbsp;&nbsp;= u : acc<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| otherwise&nbsp;= acc</p>
<p>allNodes                     :: (Eq a) =&gt; [(a,a)] -&gt; [a]<br />
allNodes []                    = []<br />
allNodes [(u,v)]            = [u,v]<br />
allNodes ((u,v):gs)        = nub (u : v : allNodes gs) </p>
<p>allPaths' l g acc<br />
&nbsp;&nbsp;&nbsp;&nbsp;| length acc == length paths&nbsp;= acc<br />
&nbsp;&nbsp;&nbsp;&nbsp;| otherwise&nbsp;= allPaths' l g (nub (acc ++ paths))<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;paths = nub (appendNeighboursToPaths l acc g)</p>
<p>appendNeighboursToPaths l [] _ = []<br />
appendNeighboursToPaths l  (p:ps) g<br />
&nbsp;&nbsp;&nbsp;&nbsp;= p : nub (appendNeighboursToPath l p g ++ appendNeighboursToPaths l ps g)</p>
<p>appendToAll l [] _	= []<br />
appendToAll l (x:xs) y	= maybeAdded : appendToAll l xs y<br />
&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;maybeAdded&nbsp;&nbsp;| elem y x = x<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| length (x) &gt; (l-1) = x<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| otherwise	= x ++ [y]</p>
<p>flatten = foldl (++) []</p>
<p>-------------------------------------------------------------------------------<br />
-- Test code below<br />
-------------------------------------------------------------------------------</p>
<p>test=do putStr "\n"<br />
	putStr "Simple tests to check return length of path lists\n"<br />
	putStr "1  == length (findAllPaths 100 'a' g0)?  " ;<br />
		print (1 == length (findAllPaths 100 'a' g0))<br />
	putStr "5  == length (findAllPaths 100 'a' g1)?  " ;<br />
		print (5 == length (findAllPaths 100 'a' g1))<br />
	putStr "9  == length (findAllPaths 100 'a' g2)?  " ;<br />
		print (9 == length (findAllPaths 100 'a' g2))<br />
	putStr "9  == length (findAllPaths 100 'a' g3)?  " ;<br />
		print (9 == length (findAllPaths 100 'a' g3))<br />
	putStr "4  == length (findAllPaths 100 'a' g4)?  " ;<br />
		print (4 == length (findAllPaths 100 'a' g4))<br />
	putStr "21 == length (findAllPaths 100 'a' g5)?  " ;<br />
		print (21 == length (findAllPaths 100 'a' g5))<br />
	putStr "\n"<br />
	putStr "2 == length (findAllPathsTo 100 'a' 'f' g5)? " ;<br />
		print (2 == length (findAllPathsTo 100 'a' 'f' g5))<br />
	putStr "1 == length (findAllPathsTo 6 'a' 'f' g5)?   " ;<br />
		print (1 == length (findAllPathsTo 6 'a' 'f' g5))<br />
	putStr "0 == length (findAllPathsTo 100 'a' 'z' g5)? " ;<br />
		print (0 == length (findAllPathsTo 100 'a' 'z' g5))<br />
	putStr "\n"<br />
	putStr "Has all paths  [\"abcdf\",\"abcjklmnf\"] in (findAllPathsTo 100 'a' 'f' g5)? " ;<br />
		print (checkSameContents (findAllPathsTo 100 'a' 'f' g5) ["abcdf","abcjklmnf"])<br />
	putStr "Has all paths  [\"abcdf\"] in (findAllPathsTo 6 'a' 'f' g5)?               " ;<br />
		print (checkSameContents (findAllPathsTo 6 'a' 'f' g5) ["abcdf"])</p>
<p>g0=[('a','a'),('b','b'),('c','c')]<br />
g1=[('a','b'),('b','c'),('c','d'),('d','e')]<br />
g2=[('a','b'),('b','c'),('c','d'),('c','e'),('d','f'),('e','f')]<br />
g3=[('a','b'),('b','c'),('c','d'),('c','e'),('d','f'),('e','g'),('g','h'),('h','i')]<br />
g4=[('a','b'),('b','c'),('b','d')]<br />
g5=[('a','b'),('b','c'),('c','d'),('c','e'),('d','f'),('e','g'),('g','h'),('h','i'),('c','j'),('j','k'),('k','l'),('l','m'),('m','n'),('n','f')]</p>
<p>checkSameContents&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:: (Eq a) =&gt; [a] -&gt; [a] -&gt; Bool<br />
checkSameContents a b<br />
&nbsp;&nbsp;&nbsp;&nbsp;= (length a == length b) &amp;&amp; (length b) == (length (takeWhile f a))<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f x = elem x b</p>
<p></code></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whatimean.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whatimean.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/108/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/108/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/108/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=108&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2009/10/21/finding-all-the-paths-in-a-graph-with-haskell/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>Playing with Servos and SUN SPOTS</title>
		<link>http://whatimean.wordpress.com/2009/09/07/playing-with-servos-and-sun-spots/</link>
		<comments>http://whatimean.wordpress.com/2009/09/07/playing-with-servos-and-sun-spots/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 14:06:06 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Sun SPOT]]></category>
		<category><![CDATA[Servo]]></category>
		<category><![CDATA[SUNSPOTS]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=99</guid>
		<description><![CDATA[Introduction I&#8217;ve managed to find some time recently to get playing with my SUN SPOTs again, so I figured I&#8217;d start by wiring up one of the servos from my ancient remote control cars to it. Although, there seems to be a lot of information about doing this on the web (mostly the wiring diagrams) [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=99&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>
I&#8217;ve managed to find some time recently to get playing with my SUN SPOTs again, so I figured I&#8217;d start by wiring up one of the servos from my ancient remote control cars to it.  Although, there seems to be a lot of information about doing this on the web (mostly the wiring diagrams) I hit a snag with getting the full motion range out of my servo.  So I figured I&#8217;d put something up here in case anyone else encounters the same.
</p>
<h2>Scenario</h2>
<p>
To control my servo I wrote a very quick GUI that allowed me to send float values through the connected base station to the free range SUN SPOT.  That SPOT was wired up to a battery pack and servo and the servo moved when I hit the GUIs button.  Simple, but a nice first step.
</p>
<h2>The Setup</h2>
<p>
I mostly copied the wiring of the servos from <a href="http://fantastickobe.blogspot.com/2008/05/servo-car-sun-spot-app-3.html">&#8220;Fantastic Kobe&#8221;</a> and this <a href="http://blogs.sun.com/davidgs/entry/how_to_attach_servo_motors">offical SUN blog</a>.  There&#8217;s not a lot to the wiring, as you can see from this picture.
</p>
<div id="attachment_100" class="wp-caption aligncenter" style="width: 460px"><img src="http://whatimean.files.wordpress.com/2009/09/imgp3485.jpg?w=450&#038;h=337" alt="Shows the wiring from the battery pack and SUNSPOT to the Servo" title="Servo Wiring" width="450" height="337" class="size-full wp-image-100" /><p class="wp-caption-text">Shows the wiring from the battery pack and SUNSPOT to the Servo</p></div>
<p>
I not going to go into detail about what connects where, because that information can easily be found on either of the above two links.
</p>
<h3>Setting the Servo Bounds</h3>
<p>
One of the things I found was using the <font face="courier">setPosition(float p)</font> method on <font face="courier">Servo</font> wasn&#8217;t giving me the full range of motion.  To fix this you need to set the bounds of your particular servo.  I didn&#8217;t know the &#8216;correct&#8217; way to do this, so instead I went with a trial-and-error approach.
</p>
<p><code>    private int servoPin = EDemoBoard.H1;</p>
<p>    private void initServo() {<br />
        servo = new Servo(EDemoBoard.getInstance().getOutputPins()[servoPin]);<br />
//        for(int i=250; i&lt;2300; i+=10) {<br />
//            servo.setValue(i);<br />
//            out(&quot;value=&quot;+i);<br />
//            Utils.sleep(100);<br />
//        }<br />
        servo.setBounds(250, 2300);<br />
    }</code></p>
<p>
In the above code, the starting value of &#8220;i&#8221; was originally zero and the end value was 10000.  Then, by using changing these values so that when <font face="courier">initServo()</font> was called the servo didn&#8217;t groan in protect, I was able to set the bounds as shown.  Having done that, <font face="courier">servo.setValue(0.5);</font> puts the servo in the middle as expected.  With values of 0 and 1.0 taking the servo to its extremes.
</p>
<p>
I expect that most people&#8217;s servos are going to be different.  Mine is a Futaba FP-S148.  And now I can move a servo around, I can start to do something useful (or at least fun) with it!
</p>
<h2>The Code (Free Range SPOT)</h2>
<p>There is only one class in the application that sits on the free range SPOT.<br />
<code>import java.io.IOException;</p>
<p>import javax.microedition.io.Connector;<br />
import javax.microedition.io.Datagram;<br />
import javax.microedition.io.DatagramConnection;<br />
import javax.microedition.midlet.MIDlet;<br />
import javax.microedition.midlet.MIDletStateChangeException;<br />
import com.sun.spot.sensorboard.EDemoBoard;<br />
import com.sun.spot.sensorboard.peripheral.Servo;</p>
<p>public class MainApplication extends MIDlet {<br />
&nbsp;&nbsp;&nbsp;&nbsp;private final String BASE_STATION_ID = "0014.4F01.0000.103E";</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private int servoPin = EDemoBoard.H1;<br />
&nbsp;&nbsp;&nbsp;&nbsp;private Servo servo;<br />
&nbsp;&nbsp;&nbsp;&nbsp;private DatagramConnection toBaseStation = null;</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;protected void destroyApp(boolean arg0) throws MIDletStateChangeException {}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;protected void pauseApp() {}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;protected void startApp() throws MIDletStateChangeException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;initComms();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;initServo();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void initComms() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;toBaseStation = (DatagramConnection) Connector.open("radiogram://" + BASE_STATION_ID + ":100");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;startListenerThread();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (IOException ex) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out("EXCEPTION: "+ex.getMessage());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void initServo() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;servo = new Servo(EDemoBoard.getInstance().getOutputPins()[servoPin]);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;servo.setBounds(250, 2300);<br />
//        for(int i=200; i&lt;2300; i+=10) {<br />
//            servo.setValue(i);<br />
//            out(&quot;value=&quot;+i);<br />
//            Utils.sleep(100);<br />
//        }<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void startListenerThread() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Thread t = new Thread(new Runnable() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;public void run() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;while(true) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;listenForMessage();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;});<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t.start();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void listenForMessage() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Datagram dgIn = null;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dgIn = toBaseStation.newDatagram(toBaseStation.getMaximumLength());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;toBaseStation.receive(dgIn);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleMessage(dgIn.readUTF());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (IOException ex) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out(&quot;EXCEPTION LISTENING: &quot;+ex.getMessage());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ex.printStackTrace();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void handleMessage(String message) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out(&quot;NEW MESSAGE [&quot;+message+&quot;]&quot;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(message.startsWith(&quot;SERVO:&quot;)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleServoMessage(message);<br />
&nbsp;&nbsp;&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;handleUnknownMessage(message);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void handleUnknownMessage(String message) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out(&quot;UnknownMessage [&quot;+message+&quot;]&quot;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sendMessage(&quot;UNKNOWN MESSAGE [&quot;+message+&quot;]&quot;);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void handleServoMessage(String message) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int cutAt = message.indexOf(&quot;:&quot;)+1;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String txtValue = message.substring(cutAt);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;float value = Float.valueOf(txtValue).floatValue();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(value  1.0) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sendMessage("SERVO VALUE REJECTED.  OUT OF BOUNDS 0.0-1.0 ("+txtValue+")");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;servo.setPosition(value);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sendMessage("SERVO: New Value Set="+servo.getValue());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (NumberFormatException nfe) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;sendMessage("SERVO VALUE REJECTED.  NOT A VALID FLOAT ("+txtValue+")");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void sendMessage(String message) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out("Sending: "+message);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Datagram dgOut = null;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dgOut = toBaseStation.newDatagram(toBaseStation.getMaximumLength());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dgOut.writeUTF(message);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;toBaseStation.send(dgOut);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} catch (IOException e) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out("EXCEPTION SENDING TO BS: "+e.getMessage());<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} finally {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(null != dgOut) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;dgOut.reset();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;private void out(String msg) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(msg);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}</p>
<p>}</code></p>
<h2>The Code (Base Station)</h2>
<p>
The code on the base station is simple enough, in fact too simple to warrent posting and spending the time formatting it here.  The only interesting bit is the following line which is one of the first lines in the <font face="courier">public static void main(String[] args)</font> method;
</p>
<p><code>OTACommandServer.getInstance().start();</code></p>
<p>
The rest of the code is either UI/Swing code or normal Java/SUN SPOT code.  In fact, the initComms, sendMessage, startListenerThread and listenForMessage methods are identical to those that run on the free range SPOT.  The only difference is the SPOT address that the DatagramConnection is opened with.  Obviously, on the free range SPOT it is opened with the address of the base station, and the reverse for the code on the base station.
</p>
<h2>Aside</h2>
<p>
Disclaimer: Obviously, soldering is dangerous to yourself and the components you&#8217;re working on/with.  Any damage or injury you sustain following this advice is entirely at your own risk and I accept no responsibilty for it.
</p>
<p>
&#8230;that being said; if you don&#8217;t have a decent breakout board for your SUN SPOTs (and you&#8217;re in the UK) then Maplin do some PCB socket connector things* that you can buy and solder into your SUN SPOT.  This gives you the ability to use bread board connector cables to easily connect up different sockets from the SUN SPOT without having to do any resoldering.  The soldering its self is a bit fiddly, so I recommend getting a decent magnifying glass and a soldering iron with a fine tip.  I&#8217;m definitely not the worlds best solder-er but I managed it okay.
</p>
<p>
* &#8211; I forget the actual name or catalogue reference, they&#8217;re pretty cheap (less than a pound I think) and are sold in rows of about 20 or so.  You just snap off two rows of 10 each and get on with it.</p>
<h2>Useful Links</h2>
<ul>
<li><a href="http://www.sunspotworld.com/docs/Purple/javadoc/index.html?com/sun/spot/sensorboard/peripheral/Servo.html">SUN SPOT API Doc</a></li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whatimean.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whatimean.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/99/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/99/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/99/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=99&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2009/09/07/playing-with-servos-and-sun-spots/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>

		<media:content url="http://whatimean.files.wordpress.com/2009/09/imgp3485.jpg" medium="image">
			<media:title type="html">Servo Wiring</media:title>
		</media:content>
	</item>
		<item>
		<title>Playing with the Sun SPOT Radio</title>
		<link>http://whatimean.wordpress.com/2008/12/18/playing-with-the-sun-spot-radio/</link>
		<comments>http://whatimean.wordpress.com/2008/12/18/playing-with-the-sun-spot-radio/#comments</comments>
		<pubDate>Thu, 18 Dec 2008 15:31:13 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Sun SPOT]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=72</guid>
		<description><![CDATA[I have recently been lucky enough to borrow a set of very cool Sun SPOTs, so I immediately began thinking of all the amazingly clever and brilliant things I could do with them. However, with the exception of making the LEDs light up like a Cylon&#8217;s eyes (or Knightrider&#8217;s Kit as per your preference), all [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=72&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have recently been lucky enough to borrow a set of very cool <a href="http://www.sunspotworld.com/">Sun SPOTs</a>, so I immediately began thinking of all the amazingly clever and brilliant things I could do with them.  However, with the exception of making the LEDs light up like a Cylon&#8217;s eyes (or Knightrider&#8217;s Kit as per your preference), all my ideas required one spot to be able to talk to another.</p>
<p>So what I figured the first thing to do would be to create a simple way to do this.  Basically, each SPOT you want to talk to another instantiates a <font face="Courier">Buddy</font> object and asks it to look for another buddy (<font face="Courier">myBuddy.lookForPair()</font>) this will then start the buddy broadcasting and looking for a fellow.</p>
<p>It&#8217;s probably important to note at this point that I have <em>not</em> tested this code with more than two SPOTs, I certainly haven&#8217;t tested any edge cases where multiple SPOTs start up and all start looking for buddies on different ports.  This is code is for my own use, I&#8217;m very happy for anyone to download, modify and use it (it is GPL&#8217;d) as long as you remember that it only works for the nicest of use cases.</p>
<p>Once two buddies (on different SPOTs) have connected you can send a message from one to the other by typing;<br />
<pre class="brush: java;">
myBuddy.sendMessage(&quot;my message&quot;);
</pre></p>
<p>Recieved messages are handled by a <font face="Courier">BuddyListener</font> which your SPOT application should have given to it&#8217;s Buddy instance.  Recieved messages come in from the following method on that interface;<br />
<pre class="brush: java;">
void messageRecieved(String message);
</pre></p>
<p>There&#8217;s lots of ways this code could be improved, for example the initial broadcast port is hardcoded into the Buddy code itself, this should really be parameterised.  Also, the sleeps and waits that the Buddy endures while trying to connect to another one and so on.  These should probably be pulled out to fields so that they can be tweaked more easily.</p>
<p>The good thing about this code is that it makes paired communication very simple (although you do have to be careful with the threads that are listening to incoming messages).  You can also use your own language/protocol that the SPOTs will interpret on top of this Buddy mechanism very easily.</p>
<p><b>radio.Buddy</b> &#8211; This is the meat of the project.  To easily connect two SPOTs each must have an instance of one of these.  Once connected to each other sending and recieving messages between the two is very easy.<br />
<pre class="brush: java;">
/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package radio;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;

import com.sun.spot.io.j2me.radiogram.RadiogramConnection;
import com.sun.spot.io.j2me.radiostream.RadiostreamConnection;
import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.util.IEEEAddress;
import com.sun.spot.util.Utils;
import com.sun.squawk.util.StringTokenizer;

public class Buddy {

	private static final String NEED_BUDDY = &quot;BUDDY_REQ&quot;;
	private static final String I_WILL_BE_YOUR_BUDDY = &quot;BUDDY_ACK&quot;;

	private long thisAddressAsNumber = RadioFactory.getRadioPolicyManager().getIEEEAddress();
	private String addyStr;

	private RadiostreamConnection listenOn;
	private RadiostreamConnection sendOn;

	private DataInputStream listenOnInputStream;
	private DataOutputStream sendOnOutputStream;

	private int portOut;
	private int portIn;

	private BuddyListener buddyListener = new NullBuddyListener();

	private int initialBroadCastPort;

	private boolean foundBuddy = false;

	private RadiogramConnection broadcastConnectionIn;
	private DatagramConnection broadcastConnectionOut;

	private int MAX_BROADCAST_SIZE;

	public Buddy(int broadcastPort) throws IOException {
		this.initialBroadCastPort = broadcastPort;
	}

	public void lookForPair() throws IOException {
		IEEEAddress addy = new IEEEAddress(RadioFactory.getRadioPolicyManager().getIEEEAddress());
		addyStr = addy.asDottedHex();

		System.out.println(&quot;I am &quot; + addyStr);

		broadcastConnectionIn = (RadiogramConnection) Connector.open(&quot;radiogram://:&quot; + initialBroadCastPort);
		MAX_BROADCAST_SIZE = broadcastConnectionIn.getMaximumLength();
		broadcastConnectionOut = (DatagramConnection) Connector.open(&quot;radiogram://broadcast:&quot; + initialBroadCastPort);
		startListenForPartnerResponseThread();
		startLookForBuddyThread();
	}

	public void setBuddyListener(BuddyListener bl) {
		
		if(null != bl) {
			buddyListener = bl;
		} else {
			buddyListener = new NullBuddyListener(); //allows us to reset the currently loaded BuddyListener
		}
		
	}

	public void sendMessage(String message) {
		if (null != sendOn) {
			try {
				if (null == sendOnOutputStream) {
					sendOnOutputStream = sendOn.openDataOutputStream();
				}
				sendOnOutputStream.writeUTF(message);
			} catch (IOException ioe) {
				System.out.println(&quot;IOException sending message on partner stream&quot;);
				ioe.printStackTrace();
			}
		} else {
			throw new IllegalStateException(
					&quot;Cannot send message.  No buddy found yet.&quot;);
		}
	}

	private void startLookForBuddyThread() {
		Thread t = new Thread(new Runnable() {
			public void run() {
				lookForBuddy();
			}
		});
		t.start();
	}

	private void lookForBuddy() {
		try {
			while (!foundBuddy) {
				Datagram dg = broadcastConnectionOut.newDatagram(broadcastConnectionOut.getMaximumLength());
				dg.writeUTF(Buddy.NEED_BUDDY + &quot; &quot; + initialBroadCastPort);
				broadcastConnectionOut.send(dg);

				Utils.sleep(1000);
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

	private void startListenForPartnerResponseThread() {
		Thread t = new Thread(new Runnable() {
			public void run() {
				try {
					while (true) {
						Datagram dg = broadcastConnectionIn.newDatagram(MAX_BROADCAST_SIZE);
						broadcastConnectionIn.receive(dg); // blocking call

						String message = dg.readUTF();

						String otherAddress = dg.getAddress();
						long otherAddressAsNumber = IEEEAddress.toLong(otherAddress);

						if (thisAddressAsNumber != otherAddressAsNumber) {
							handleIncomingBroadcastMessage(dg, message,	otherAddress);
						}
						if (sendOn != null &amp;&amp; listenOn != null) {

							System.out.println(&quot;Buddy status achieved, no longer going to listen to broadcasts&quot;);
							System.out.println(&quot;Partner port to send on: &quot; + sendOn.getLocalPort());
							System.out.println(&quot;Partner port to listen on: &quot; + listenOn.getLocalPort());

							startListenOnPartnerStreamThread();
							break;
						}
					}

				} catch (IOException ioe) {
					System.out.println(&quot;Exception when listening for buddy response&quot;);
					ioe.printStackTrace();
				}
			}
		});
		t.start();

	}

	private void handleIncomingBroadcastMessage(Datagram dg, String message, String otherAddress) throws IOException {
		if (message.startsWith(Buddy.NEED_BUDDY)) {
			if (null == sendOn) {
				int otherPort = Integer.valueOf(separateStrings(message)[1]).intValue();
				Datagram response = offerToBeBuddy(otherPort, otherAddress);

				response.setAddress(dg);
				broadcastConnectionIn.send(response);
			}
		} else if (message.startsWith(Buddy.I_WILL_BE_YOUR_BUDDY)) {
			buddyInviteAccepted(message, otherAddress);
		}
	}

	private void buddyInviteAccepted(String message, String otherAddress)	throws IOException {
		foundBuddy = true;

		portOut = Integer.valueOf(separateStrings(message)[1]).intValue();
		sendOn = (RadiostreamConnection) Connector.open(&quot;radiostream://&quot; + otherAddress + &quot;:&quot; + portOut);

		portIn = portOut - 1;
		listenOn = (RadiostreamConnection) Connector.open(&quot;radiostream://&quot; + otherAddress + &quot;:&quot; + portIn);
	}

	private Datagram offerToBeBuddy(int otherPort, String otherAddress) throws IOException {
		foundBuddy = true;

		portOut = otherPort;
		portIn = portOut + 1;

		System.out.println(&quot;Offering to be a buddy to &quot; + otherAddress + &quot;\nSending on &quot; + portOut + &quot;\nListening on &quot; + portIn);

		sendOn = (RadiostreamConnection) Connector.open(&quot;radiostream://&quot; + otherAddress + &quot;:&quot; + portOut);
		Datagram response = broadcastConnectionIn.newDatagram(MAX_BROADCAST_SIZE);

		response.writeUTF(Buddy.I_WILL_BE_YOUR_BUDDY + &quot; &quot; + portIn);
		listenOn = (RadiostreamConnection) Connector.open(&quot;radiostream://&quot; + otherAddress + &quot;:&quot; + portIn);
		return response;
	}

	private void startListenOnPartnerStreamThread() {
		Thread t = new Thread(new Runnable() {
			public void run() {
				while (true) {
					listenForIncomingMessage();
				}
			}
		});
		t.start();
	}

	private void listenForIncomingMessage() {
		if (null != listenOn) {

			try {
				if (null == listenOnInputStream) {
					listenOnInputStream = listenOn.openDataInputStream();
				}

				String message = listenOnInputStream.readUTF();
				buddyListener.messageRecieved(message);

			} catch (IOException ioe) {
				System.out.println(&quot;IOException recieving message on partner stream&quot;);
				ioe.printStackTrace();
			}
		} else {
			// Maybe we haven't found a partner yet, so don't spin the processor
			Utils.sleep(100);
		}
	}

	private String[] separateStrings(String msg) {
		StringTokenizer stk = new StringTokenizer(msg, &quot; &quot;);
		String[] result = new String[stk.countTokens()];
		for (int i = 0; stk.hasMoreTokens(); i++) {
			result[i] = stk.nextToken();
		}
		return result;
	}
}
</pre></p>
<p><b>radio.BuddyListener</b> &#8211; Classes wishing to have a buddy must have (or be) one of these and give it to the buddy instance<br />
<pre class="brush: java;">
/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package radio;

public interface BuddyListener {
	void messageRecieved(String message);
}
</pre></p>
<p><b>radio.NullBuddyListener</b> &#8211; It might be that two buddies are connected and one could be chatting to the other which doesn&#8217;t have a <font>BuddyListener</font> attached, in which case this is used instead.<br />
<pre class="brush: java;">
/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package radio;

public class NullBuddyListener implements BuddyListener {

	public void messageRecieved(String message) {
		System.out.println(&quot;Warning!  NullBuddyListener being used and messages are getting recieved&quot;);
	}
}
</pre></p>
<p><b>radio.RadioFun</b> &#8211; This is included for completeness.  It&#8217;s the app that got run when I was testing the Buddy connections.  I don&#8217;t think it makes a lot of sense for any one else to use this class except to see how to talk/listen to the buddy.<br />
<pre class="brush: java;">
/* 
 * This program is free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation; either version 2 of the License, or 
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 * for more details.
 * 
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */
package radio;

import java.io.IOException;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import com.sun.spot.peripheral.radio.RadioFactory;
import com.sun.spot.util.IEEEAddress;
import com.sun.spot.util.Utils;

public class RadioFun extends MIDlet {

	private Buddy buddy;
	
	public RadioFun() {
	}

	void start() {
		try {
			buddy = new Buddy(60);		
			buddy.setBuddyListener(new BuddyListener() {
				public void messageRecieved(String message) {
					System.out.println(&quot;recieved=[&quot;+message+&quot;]&quot;);
				}
			});
			buddy.lookForPair();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

		IEEEAddress addy = new IEEEAddress(RadioFactory.getRadioPolicyManager().getIEEEAddress());
		String addyStr = addy.asDottedHex();
		
		while (true) {
			try {
				buddy.sendMessage(&quot;Hello from &quot;+addyStr);
			} catch (IllegalStateException ise) {
				System.out.println(&quot;Failed to send message [&quot;+ise.getMessage()+&quot;]&quot;);
			}
				
			Utils.sleep(500);
		}
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
	}

	protected void pauseApp() {
	}

	protected void startApp() throws MIDletStateChangeException {
		RadioFun rf = new RadioFun();
		rf.start();
	}
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whatimean.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whatimean.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/72/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/72/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/72/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=72&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/12/18/playing-with-the-sun-spot-radio/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>Putting The Pain Into Teamwork</title>
		<link>http://whatimean.wordpress.com/2008/10/30/putting-the-pain-into-teamwork/</link>
		<comments>http://whatimean.wordpress.com/2008/10/30/putting-the-pain-into-teamwork/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 17:23:01 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[best practise]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[quality]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[Team work]]></category>
		<category><![CDATA[Java Team Work Software Programming]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=56</guid>
		<description><![CDATA[Introduction Looking back at code I wrote ages ago often leaves me wondering &#8220;What idiot wrote this junk?&#8221; Looking back through articles I&#8217;ve written gives me an uncomfortably similar feeling. Today I&#8217;m thinking specifically about multiple return points, which I announced to be the root of much evil in this post. What this post reminds [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=56&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>
Looking back at code I wrote ages ago often leaves me wondering &#8220;What idiot wrote this junk?&#8221;  Looking back through articles I&#8217;ve written gives me an uncomfortably similar feeling.  Today I&#8217;m thinking specifically about multiple return points, which I announced to be the root of much evil in <a href="http://whatimean.wordpress.com/2007/02/08/multiple-return-points-are-bad">this post</a>.  What this post reminds me about most, though, is the <em>Do What Makes Sense</em> principle, something that I&#8217;ve often claimed to subscribe to.
</p>
<h2>How do you plead?</h2>
<p>
I have to confess my guilt before I can continue.  I&#8217;ve recently started writing some methods which have more than one return point (and I&#8217;m not just talking about exceptions here).  But as a kind of mitigation I only use them in very small methods and only sometimes.
</p>
<p>
Actually that&#8217;s not true either.
</p>
<p>
There is a certain kind of method where multiple return points are acceptable, like these;
</p>
<p><code><br />
public Object myMethod() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;if(comeCondition) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return someObject;<br />
&nbsp;&nbsp;&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return someOtherObject;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}<br />
</code></p>
<p>
Or this one;
</p>
<p><code><br />
public Object myOtherMethod() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;switch (something) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 1:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return something1;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 2:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return something2;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 3:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return something3;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 4:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return something4;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;case 5:<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return something5;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}<br />
</code></p>
<p>
But in these examples the methods are doing very specific things, most plainly, they return something.  No other processing is done.  I would still say <font face="Courier">return</font>s dotted around throughout a method is still a Bad Thing.  But that&#8217;s not what got me thinking.  Whilst trying to justify this use of MRP to myself I started running through the reasons why this code is acceptable, when previously I had said it wasn&#8217;t.  The <font face="Courier">switch</font> method above reminds me of some refactoring work I did on my company&#8217;s product a while back, and it&#8217;s the fallout from that refactoring that I ended thinking about the most.
</p>
<h2>The Situation</h2>
<p>
Here&#8217;s some background.  I work for a company which produces (and uses) it&#8217;s own software product, this product allows the buying and selling of Widgets.  There are many different places that we can buy and sell Widgets from using our software, there is also a piece of third party software which we must tell who has purchased what Widgets, from whom and how many.  The problem comes from the fact that each the objects which represent a user&#8217;s Widget-trading position is different for each Widget Gateway.  Further, the position objects which we must send to the third party software is fixed.  What&#8217;s even worse, is that each Widget Gateway can be further subdivided into more specific kinds of Widget Position Objects.  Again, it&#8217;s even worse than that.
</p>
<p>
The <font face="Courier">AcmeWidgetPositionSubA</font> class and the <font face="Courier">AcmeWidgetPositionSubB</font> class both have the same attributes, but because one is &#8230;SubA and one is &#8230;SubB, when translating this to a <font face="Courier">ThirdPartyWidgetPosition</font> the attributes with the same <em>name</em> in the &#8230;SubA/B classes will be mapped to <em>different</em> attributes in the <font face="Courier">ThirdPartyWidgetPosition</font> class.
</p>
<p>
For example; <font face="Courier">AcmeWidgetPositionSubA.getSpecialCode()</font> needs to be mapped to <font face="Courier">ThirdPartyWidgetPosition.getCode()</font>.  But <font face="Courier">AcmeWidgetPositionSubB.getSpecialCode()</font> needs to be mapped to <font face="Courier">ThirdPartyWidgetPosition.getSystemCode()</font>.
</p>
<p>
This is the scope of the problem and the existing code to do this was lots of lines of if&#8230;then&#8230;elses to get the right things into the write place before the <font face="Courier">ThirdPartyWidgetPosition</font> is sent to the third party software for processing.  Further, there each subtype of Widget Gateway had it&#8217;s own chunk of if&#8230;then&#8230;else code of varying complexity to get the job done specific to itself.  To refactor this code I got rid of all the if&#8230;then&#8230;else functionality and put all the logic into the type system.  By introducing some extra classes that had only overloaded constructors I could remove every occurance of if&#8230;then&#8230;else, create a <font face="Courier">AcmeWidgetPositionSub<i>X</i></font> object, cast it to a <font face="Courier">ThirdPartyWidgetPosition</font> and have everything in the right place, as if by magic.
</p>
<p>
So far so good, lots of complex nested branches get removed, all the unit tests pass, everything works, we all go home happy.  Now fast forward a couple of months.  Someone else is looking at the code and they are struggling to see what goes where and how the branched code has been removed in favour of a clever type hierarchy.  Now, let me first explain that it&#8217;s my opinion that having the logic inside the type system is a better, actually less complex and cleaner implementation approach than if&#8230;then&#8230;else.  It just feels &#8220;more OO&#8221;; even if I can&#8217;t quantify that phrase particularly well.  But to a team member who is more used to seeing and reading if&#8230;then&#8230;else structures it is not cleaner and more obvious.  It&#8217;s something that they need to wrestle with and really <em>read</em> in order to understand it.
</p>
<p>
So if I have slowed down the work of a team member, if I have caused them extra effort to do their own tasks, is my approach still the better one?  Even if the code I wrote was the &#8220;more correct&#8221; implementation; was it the right code to write because of the affect it had on someone else?
</p>
<h2>Style Over Substance</h2>
<p>
A few more of my little foibles are using <font face="Courier">Boolean.TRUE</font> rather than the primative <font face="Courier">true</font>, and putting the literal I am comparing as the first operand of <font face="Courier">equals</font> &#8211; even though I know that the protection this offers me is irrelevant given I spend most of my time writing Java<sub>1</sub>.  I know, because I have been told, that some people find these things more difficult to read than their more usual alternatives.  Personally I don&#8217;t understand why they are more confusing to read.  But given that I can read the code quite happily either way and given that the compiler will change my code to whatever it feels like; should I be tailoring my professional coding style so as the most number of team members are happiest reading it?
</p>
<h2>Drawing The Line</h2>
<p>
The answer, as everything when discussing &#8216;programming best practise&#8217;, is; &#8220;it depends&#8221;.  In the first example with the types vs if&#8230;then&#8230;else, that change should definitely be made.  I can sit down with you and discuss why it is better, what benefits it has, show you how it is easier to extend etc.  And as a consequence of that discussion, the team members who will be reading that code will hopefully start to learn from that example and we&#8217;ll be seeing fewer and fewer nested-branched code.  Designs will become cleaner and gradually the overall quality of the code across the project will get better.
</p>
<p>
But what of more style based differences, or indeed, anything else which you can&#8217;t prove is a tangible benefit?  If they cause pain for other team members or get in the way, then I suggest always defaulting to the lowest common denominator<sub>2</sub>.  That might be structuring code for the least experienced developer &#8211; <em>as long as such structuring does not compromise quality in any way</em>.  Or at least, structuring your code so that it is consistent with the rest of the code base.  It means shoe-horning your coding style into the style used in the rest of the code base to make it easier to read for the whole team &#8211; this is especially true in large legacy codebases.
</p>
<p>
Doing these kinds of silly superficial things in difference to the rest of the code base is something that I am guilty of, and on reflection, something that I should be trying much harder to put a stop to.  Make my code blend more seamlessly into the rest of the code is going to make reading it easier for everyone.  But beware, when there is a real change that should be made, for a real reason with benefits that can be quantified I will still argue for that change &#8211; even if it&#8217;s out of the comfort zone of those around me.  And I fully expect, nay demand, that those around make those same kinds of changes to pull me out of my comfort zone &#8211; because that&#8217;s the only way I&#8217;m going to become a better programmer.
</p>
<p>
There is a lot of talk in various technical blogs about how superstar programmers should be allowed to express themselves in any way, structure their code the way they think it should be done, and basically do whatever they want because (you know) they&#8217;re superstars.  Most of us are probably not superstars and most of the teams we work in are probably not 100% made up of superstars, so I really don&#8217;t find those arguments compelling.  What I do find compelling is trying to increase the average code quality and the skill levels of the average (or lowest) team member, and these things are not measured by where they put their curly brackets or whether they use <font face="Courier">Boolean.FALSE</font> or <font face="Courier">false</font>.  These things are superficial and any non-superficial programmer should be able to get over them.
</p>
<p>
And let&#8217;s not forget; everyone of us is the average-est or the lowest skilled level programmer in the team at something.  And even if your team <i>is</i> made up of Superstars, chances are they are not all going to be the same <i>kind</i> of Superstar.  Think of your favourite classical music composer, rock performer, rap artist, solo violinist, jazz pianist and so on.  Now imagine putting them all in the same band; left to their own devices I really don&#8217;t think any music they produce is going to be bearable, let alone enjoyable &#8211; and this assumes that they&#8217;ll manage to produce anything!  Not unless they all agree to do certain things in the same or similar way and all pull in the same direction<sub>3</sub>.  And I guarantee that each one of them will feel restricted in some way by that.  But what they produce will be well worth the Superstar fees they&#8217;ll be charging!
</p>
<h2>Conclusion</h2>
<p>
It is true that a bit of sand inside an oyster will make a pearl, but a bit of sand inside your shoe is just going to make blisters on your feet.  Removing code complexity and builder and more defined cleaner design is a worthy goal and one worth fighting for.  But doing what is essentially meaningless things for no tangible benefit is not.  As with anything where more than one individual is concerns the rule of give and take must be applied.  Forcing your team members to adopt a distorted concept of Hungarian Notation is pointless.  Similarly, when such a notation has been adopted and is prevelant in a large percentage of the code base, fighting that notation is probably a hiding to nothing.
</p>
<p>
Team cohesion is important.  Every team will be working better if each member is considerate to the others.  By all means bring up the uncomfortable truths and fight to make the design and code better.  But if the benefits of what you&#8217;re fighting for are not worth the battles to win it, then it&#8217;s likely your efforts would be better spent putting for head down and servicing user requests and bug fixes.</p>
<p>1 &#8211; Unless I&#8217;m comparing booleans, of course.<br />
2 &#8211; This is not meant to be a derogatory phrase.<br />
2 &#8211; Singing from the same song-sheet even.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whatimean.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whatimean.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/56/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/56/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/56/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=56&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/10/30/putting-the-pain-into-teamwork/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>New Baby!</title>
		<link>http://whatimean.wordpress.com/2008/07/26/new-baby/</link>
		<comments>http://whatimean.wordpress.com/2008/07/26/new-baby/#comments</comments>
		<pubDate>Sat, 26 Jul 2008 13:29:51 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=42</guid>
		<description><![CDATA[A personal article this one&#8230; Rachael gave birth to Esmé Faith this morning (26th July 2008 ) at 4:20 AM BST. She weighed 7lb 2oz, for those looking for metric measurements please go to Brussels where you will (unlike here) be welcomed. Mother and baby are doing fine. Kate (2 years, 2 months old) is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=42&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A personal article this one&#8230;</p>
<p>Rachael gave birth to Esmé Faith this morning (26th July 2008 ) at 4:20 AM BST.  She weighed 7lb 2oz, for those looking for metric measurements please go to Brussels where you will (unlike here) be welcomed.</p>
<p>Mother and baby are doing fine.  Kate (2 years, 2 months old) is running around saying &#8220;You must go to sleep!  Don&#8217;t wake the baby.&#8221;  Followed by bellows of &#8220;SILENCE!&#8221;  I don&#8217;t know where she got that from.</p>
<p>On a technical aspect, I was impressed with the midwifery team, as soon as the baby was built they ran all the unit tests (developed before the baby was, naturally) and could easily indicate a successful build.</p>
<p>A small subset of pictures is below.</p>
<p><div id="attachment_43" class="wp-caption alignnone" style="width: 310px"><a href="http://whatimean.files.wordpress.com/2008/07/imgp1428.jpg"><img src="http://whatimean.files.wordpress.com/2008/07/imgp1428.jpg?w=300&#038;h=225" alt="About 15 minutes old" width="300" height="225" class="size-medium wp-image-43" /></a><p class="wp-caption-text">About 15 minutes old</p></div><br />
<br />
<div id="attachment_44" class="wp-caption alignnone" style="width: 310px"><a href="http://whatimean.files.wordpress.com/2008/07/imgp1433.jpg"><img src="http://whatimean.files.wordpress.com/2008/07/imgp1433.jpg?w=300&#038;h=225" alt="A few hours old" width="300" height="225" class="size-medium wp-image-44" /></a><p class="wp-caption-text">A few hours old</p></div><br />
<br />
<a href="http://whatimean.files.wordpress.com/2008/07/imgp1444.jpg"><img src="http://whatimean.files.wordpress.com/2008/07/imgp1444.jpg?w=300&#038;h=225" alt="" width="300" height="225" class="alignnone size-medium wp-image-45" /></a><br />
<br />
<div id="attachment_48" class="wp-caption alignnone" style="width: 310px"><a href="http://whatimean.files.wordpress.com/2008/08/p1010529.jpg"><img src="http://whatimean.files.wordpress.com/2008/08/p1010529.jpg?w=300&#038;h=225" alt="All together at home" width="300" height="225" class="size-medium wp-image-48" /></a><p class="wp-caption-text">All together at home</p></div></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/whatimean.wordpress.com/42/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/whatimean.wordpress.com/42/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whatimean.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whatimean.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/42/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/42/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/42/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=42&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/07/26/new-baby/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>

		<media:content url="http://whatimean.files.wordpress.com/2008/07/imgp1428.jpg?w=300" medium="image">
			<media:title type="html">About 15 minutes old</media:title>
		</media:content>

		<media:content url="http://whatimean.files.wordpress.com/2008/07/imgp1433.jpg?w=300" medium="image">
			<media:title type="html">A few hours old</media:title>
		</media:content>

		<media:content url="http://whatimean.files.wordpress.com/2008/07/imgp1444.jpg?w=300" medium="image" />

		<media:content url="http://whatimean.files.wordpress.com/2008/08/p1010529.jpg?w=300" medium="image">
			<media:title type="html">All together at home</media:title>
		</media:content>
	</item>
		<item>
		<title>Haskel Puzzle Solved</title>
		<link>http://whatimean.wordpress.com/2008/05/18/haskel-puzzle-solved/</link>
		<comments>http://whatimean.wordpress.com/2008/05/18/haskel-puzzle-solved/#comments</comments>
		<pubDate>Sun, 18 May 2008 20:11:39 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Haskell]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=41</guid>
		<description><![CDATA[Disclaimer Don&#8217;t expect this post to be breaking any barriers. I&#8217;ve been struggling with to solve an exercise from my Haskell Road book for the past week or so and I finally cracked it. I&#8217;d be interested to know if anyone has a better way to solve it. I&#8217;m still very much a Haskell beginner [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=41&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>Disclaimer</h1>
<p>
Don&#8217;t expect this post to be breaking any barriers.  I&#8217;ve been struggling with to solve an exercise from my <a href="http://homepages.cwi.nl/~jve/HR/">Haskell Road</a> book for the past week or so and I finally cracked it.
</p>
<p>
I&#8217;d be interested to know if anyone has a better way to solve it.  I&#8217;m still very much a Haskell beginner and haven&#8217;t gotten much past pattern matching, guards and the where clause; so try not to confuse me.
</p>
<h2>The Problem</h2>
<p>
Create a function </p>
<p><code><strong>splitList :: [a] -&gt; [([a],[a])]</strong></code></p>
<p>Which takes a list </p>
<p><code><strong>[1..5]</strong></code></p>
<p>and returns a list;</p>
<p><code><strong>[([1], [2,3,4,5]), ([1,2], [3,4,5]), ([1,2,3], [4,5]), ([1,2,3,4], [5])]</strong></code>
</p>
<h2>My Solution</h2>
<p><code><b>moveHeadToTail :: [a] -&gt; [a] -&gt; [a]<br />
moveHeadToTail (xs) (y:ys)	= xs ++ [y]</p>
<p>splitListAux		:: [a] -&gt; [a] -&gt; [([a],[a])]<br />
splitListAux (o:os) []	= [([o],os)] ++ splitListAux os [o]<br />
splitListAux (o:os) h<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| length (o:os) == 2	= [(head,os)]<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| otherwise		= [(head,os)] ++ splitListAux os head<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;where<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;head = moveHeadToTail h (o:os)</p>
<p>splitList		:: [a] -&gt; [([a],[a])]<br />
splitList (x:xs)	= splitListAux (x:xs) []</b></code></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/whatimean.wordpress.com/41/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/whatimean.wordpress.com/41/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whatimean.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whatimean.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/41/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=41&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/05/18/haskel-puzzle-solved/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
		<item>
		<title>Why Can&#8217;t Java Do That?</title>
		<link>http://whatimean.wordpress.com/2008/05/15/why-cant-java-do-that/</link>
		<comments>http://whatimean.wordpress.com/2008/05/15/why-cant-java-do-that/#comments</comments>
		<pubDate>Thu, 15 May 2008 20:56:35 +0000</pubDate>
		<dc:creator>Tom</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://whatimean.wordpress.com/?p=40</guid>
		<description><![CDATA[So this year I&#8217;m trying to make in-roads in learning some new languages, in particular Ruby and Haskell. My problem is now that since I pay my bills by writing Java code every day I&#8217;m left thinking &#8220;That&#8217;s one line in Ruby&#8221; or &#8220;Why can&#8217;t Java do this like Haskell?&#8221; Without these changes I will [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=40&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>So this year I&#8217;m trying to make in-roads in learning some new languages, in particular Ruby and Haskell.  My problem is now that since I pay my bills by writing Java code every day I&#8217;m left thinking &#8220;That&#8217;s one line in Ruby&#8221; or &#8220;Why can&#8217;t Java do this like Haskell?&#8221;</p>
<p>Without these changes I will spend each day being a little bit more gumpy than is necessary.  This is bad because I vocalise my grumpiness.  (I like to think of it as contributing to the team.)  So if I&#8217;m grumpy, I&#8217;ll make those around me grumpy.  And in turn, they&#8217;ll make the ones around them grumpy.  So without these changes and with a few more hops like that <a href="http://en.wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon">Kevin Bacon</a> will be grumpy.*  So I think that it&#8217;s safe to say that even Kevin Bacon want&#8217;s these changes.  Sun is actually making Keving Bacon grumpy.  And that&#8217;s not fair.</p>
<p>So here&#8217;s a very quick, off-the-top-of-my-head, list of things that I&#8217;d like to see in Java.  I don&#8217;t care if they&#8217;re adopted as fundamental language changes or whether they&#8217;re just syntactic sugar that the compiler removes and replaces.  As long as the changes are made, I&#8217;ll be a happy bunny.</p>
<h2>Validate Method Parameters</h2>
<p>Like a good boy I always check my method parameters before I can use them.  Most of my checks are boring and repetative, they clutter up my super-important-and-complicated business method.  Why can&#8217;t they be moved out to annotations?</p>
<h3>Code Like This&#8230;</h3>
<p><code><b>public String complexMethod(Object someObj, String someStr, int number) {<br />
&nbsp;&nbsp;if(null == someObj) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;throw new IllegalArgumentException("someObj cannot be null");<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;if(null == someStr || 0 == someStr.trim().length()) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;throw new IllegalArgumentException("someStr cannot be null or empty");<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;if(MIN &gt; number || MAX &lt; number) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;throw new IllegalArgumentException("number out of range");<br />
&nbsp;&nbsp;}</p>
<p>&nbsp;&nbsp;// Complex code goes here<br />
}</b></code></p>
<h3>Is Replaced With&#8230;</h3>
<p><code><b>@Check(NOT_NULL, IllegalArgumentException, someObj, "someObj cannot be null")<br />
@Check(NOT_EMPTY, IllegalArgumentException, someStr, "someStr cannot be null or whitespace only")<br />
@Check(IN_RANGE, com.mycompany.BadNumberRangeException, number, MIN, MAX)<br />
public String complexMethod(Object someObj, String someStr, int number) {<br />
&nbsp;&nbsp;// Complex code goes here<br />
}</b></code></p>
<h2>Wrap Methods in Try-Catch</h2>
<p>Many times a day I see code where the entire method is wrapped in a try-catch statement.  Often times the stuff in the catch statement is repeated though the class (or classes).  Another annotation could remove this noise and make the business code look much more plain.</p>
<h3>Code Like This&#8230;</h3>
<p><code><b>public void doDatabaseThing() throws SQLException {<br />
&nbsp;&nbsp;try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// some database thing<br />
&nbsp;&nbsp;} catch (SQLException sqle) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;methodToRun();<br />
&nbsp;&nbsp;}<br />
}</b></code></p>
<h3>Is Replaced With&#8230;</h3>
<p><code><b>@IfThrown(java.sql.SQLException, methodToRun)<br />
public void doDatabaseThing() throws SQLException {<br />
&nbsp;&nbsp;// some database thing<br />
}</b></code></p>
<p>Maybe a better approach is to abolish all checked exceptions, but that&#8217;s another post.</p>
<h2>What was the index, please?</h2>
<p>Java&#8217;s for-each loop is just syntactic sugar for a normal for loop, complete with counter.  Why couldn&#8217;t they introduce a Perl-esque special variable that had the current iterations index in it?  For example;
<p>
<code><b>for(String name : names) {<br />
&nbsp;&nbsp;System.out.println(name + " is at index " + $_);<br />
}</b></code></p>
<h2>Controvertial: Easily implement the <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a></h2>
<p>Sometimes you need to wrap objects in other objects.  Fine.  Sometimes you can&#8217;t use a simple &#8220;extends&#8221; and just override the methods you&#8217;re interested.  Annoying.  But what happens when the object you want to wrap has an enormous public interface?  You can argue that this is implying you have a bad object model, and I probably won&#8217;t disagree, but sometimes you just have to play the cards dealt you and that means wrapping something with a big public interface.</p>
<h3>Code Like This&#8230;</h3>
<p><code><b>public class Wrapper {<br />
&nbsp;&nbsp;private Wrapped wrapped = new Wrapped();<br />
&nbsp;&nbsp;public void method1() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;wrapped.method1();<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;public void method2() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;wrapped.method2();<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;public void method3() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;//do something different first...<br />
&nbsp;&nbsp;&nbsp;&nbsp;wrapped.method3();<br />
&nbsp;&nbsp;}<br />
}</b></code></p>
<h3>Is Replaced With&#8230;</h3>
<p><code><b>@Decorates(wrapped)<br />
public class WrapperClass {<br />
&nbsp;&nbsp;private Wrapped wrapped = new Wrapped();<br />
&nbsp;&nbsp;public void method3() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;//do something different first...<br />
&nbsp;&nbsp;&nbsp;&nbsp;wrapped.method3();<br />
&nbsp;&nbsp;}<br />
}</b></code></p>
<p>&#8230;and have the compiler fill in all the boring pass-through methods for me.</p>
<h2>Pattern Matching</h2>
<p>I really like the pattern matching of methods you get in Haskell and I&#8217;m left wondering if Java might benefit from them to.</p>
<h3>Code Like This&#8230;</h3>
<p><code><b>public void doSomething(boolean flag, Object otherArg) {<br />
&nbsp;&nbsp;if (flag) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// some code here<br />
&nbsp;&nbsp;} else {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// other code here<br />
&nbsp;&nbsp;}<br />
}</b></code></p>
<h3>Is Replaced With&#8230;</h3>
<p><code><b>public void doSomething(Boolean.TRUE, Object otherArg) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// some code here<br />
}<br />
public void doSomething(Boolean.FALSE, Object otherArg) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;// other code here<br />
}</b></code></p>
<p>But I really don&#8217;t know if this makes things more simple.</p>
<h3>In Closing&#8230;</h3>
<p>I haven&#8217;t actually done much (read: any) research into how to write my own annotations in Java.  I <em>really</em> don&#8217;t know how to write an annotation that will make the compiler behave differently and inject code into the source.  I&#8217;d be interested to hear if anyone knows where I can do some reading on this.</p>
<p></p>
<p>* Okay, so it&#8217;s not a perfect application of 6-degrees, so what?</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/whatimean.wordpress.com/40/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/whatimean.wordpress.com/40/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whatimean.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whatimean.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whatimean.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whatimean.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whatimean.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whatimean.wordpress.com/40/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whatimean.wordpress.com/40/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whatimean.wordpress.com/40/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whatimean.wordpress.com&amp;blog=650809&amp;post=40&amp;subd=whatimean&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whatimean.wordpress.com/2008/05/15/why-cant-java-do-that/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/aeae87b9d3cc1f3192d8038a9908ee74?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Tom</media:title>
		</media:content>
	</item>
	</channel>
</rss>
