<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Archgrove &#187; Code</title>
	<atom:link href="http://www.archgrove.co.uk/weblog/category/programming/code/feed" rel="self" type="application/rss+xml" />
	<link>http://www.archgrove.co.uk</link>
	<description>Implicit Definition</description>
	<lastBuildDate>Thu, 05 Aug 2010 19:48:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Six to Eight development: What you might think is simple&#8230;</title>
		<link>http://www.archgrove.co.uk/weblog/2010/07/28/six-to-eight-development-getting-the-simple-things-right</link>
		<comments>http://www.archgrove.co.uk/weblog/2010/07/28/six-to-eight-development-getting-the-simple-things-right#comments</comments>
		<pubDate>Wed, 28 Jul 2010 06:00:38 +0000</pubDate>
		<dc:creator>Adam Wright</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[app]]></category>
		<category><![CDATA[iPhone]]></category>
		<category><![CDATA[sixtoeight]]></category>
		<category><![CDATA[stackoverflow]]></category>

		<guid isPermaLink="false">http://www.archgrove.co.uk/?p=185</guid>
		<description><![CDATA[This is part two of my series on writing Six to Eight, an iOS Stack Exchange client. If you haven&#8217;t read part one, I urge you to head to it now. In this part, I&#8217;ll discuss creating the first part of the &#8220;Core functionality&#8221; that users of Six to Eight will see. We&#8217;ll look at [...]]]></description>
			<content:encoded><![CDATA[<p>This is part two of my series on writing Six to Eight, an iOS Stack Exchange client. If you haven&#8217;t read <a href="http://http://www.archgrove.co.uk/weblog/2010/07/27/the-development-of-six-to-eight">part one</a>, I urge you to head to it now. In this part, I&#8217;ll discuss creating the first part of the &#8220;Core functionality&#8221; that users of Six to Eight will see. We&#8217;ll look at why I made it the way it is, and how it uses the StackExchange API.</p>
<p>Six to Eight supports all the Stack Exchange sites in the network. You &#8220;subscribe&#8221; to the sites you&#8217;re interested in, optionally focusing your attention on one person by &#8220;tracking&#8221; them. As such, the first view seen by new users of Six to Eight will be one requiring them to setup an initial subscription. You might think this should be easy, and perhaps it should be. However, for me, it turned into one of the most complex pieces of design and development in the app.</p>
<p>This &#8220;Subscription creation&#8221; view, which also allows them to edit existing subscriptions, has to accomplish three things:</p>
<ol>
<li>Let users pick a Stack Exchange site</li>
<li>Let users decide if they want to track somebody, and allow them to pick that person</li>
<li>Just get out of the way as quickly as possible for users who just want to play with the app</li>
</ol>
<p>Users have also got to be able to experiment with this setup a bit. If they&#8217;re tracking a user on one SE site, and want to switch to another, it&#8217;d be annoying if they had to re-select that user (assuming that the user is also using the newly selected site).</p>
<p>Let&#8217;s have a look at my UI attempt (<a href="http://vimeo.com/13544452">see on Vimeo</a>):</p>
<p><object width="320" height="480"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=13544452&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=13544452&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="320" height="480"></embed></object></p>
<p>The UI uses a normal iPhone table view to present the site list, and user tracking toggle. This will, hopefully, present a large number of sites in an familiar fashion. The user selector allows people to easily find their own user within the selected site, and the re-association function saves them from having to repeat this task when they experiment. The UI is nearly all non-modal, so users can change their minds and toggle options without needing to wait for data. Importantly, if they just want to close the UI and start playing, they need only wait for the sites list to load, then tap &#8220;Save&#8221;.</p>
<p>So, to the implementation. For what looks like it should be a reasonably simple presentation of data, the code that runs this view is the most complex in the entire app. This is mostly to do with the number of possible states the UI can be in, coupled with the desire to keep things happening in an asynchronous fashion &#8211; lots of background work is occurring to update the data and verify it whilst the user selects their options.</p>
<p>Initially, the view turns up in a &#8220;Loading&#8221; state &#8211; there are no sites known, no user selected. We can&#8217;t do anything until we know what sites exist in the StackExchange network. This information comes from the StackAuth API endpoint at  <span style="font-family: monospace;"><a href="http://stackauth.com/1.0/help/method?method=sites">http://stackauth.com/1.0/sites</a></span>, and Six to Eight fetchs it via my <a href="http://github.com/archgrove/CoreStack">CoreStack</a> <span style="font-family: monospace;">CSAuth</span> class. We request the data, and place the UI into a &#8220;Loading&#8221; state whilst we wait for it to arrive.  Once our delegate is called to indicate that the CoreStack background loader has the data, we can update the UI with it, and transition into a &#8220;Select a site&#8221; state, where we default to the first available site and to tracking no user.</p>
<p>The entire UI is stitched together from this type of state transition, so we might as well represent it as a finite state transition diagram. In this&#8230;</p>
<ol>
<li>Grey indicates the UI is fully operational to the user</li>
<li>Red indicates an error state, with suitable modal error message</li>
<li>Blue indicates a modal state, where the UI is displaying a &#8220;Working&#8221; dialog (like the &#8220;Look for John Doe on SESite&#8221;).</li>
<li>Green indicate &#8220;complete&#8221; states, where you can return having created a new subscription</li>
<li>Purple indicate other view controllers</li>
<li>Solid arrows are state transitions activated by the user</li>
<li>Dashed arrows are state transitions activated by the controller</li>
</ol>
<p><a href="http://www.archgrove.co.uk/wp-content/uploads/2010/07/BlogPos.png"><img src="http://www.archgrove.co.uk/wp-content/uploads/2010/07/BlogPos.png" alt="Six to Eight Site subscription state diagram" title="Six to Eight Site subscription state diagram" width="500" height="211" class="aligncenter size-full wp-image-218" /></a></p>
<p>The goal is to start in the left hand purple state (where site subscriptions are listed), and get back there via one of the green states. For clarity, I&#8217;ve omitted all the &#8220;Cancel&#8221; links back to the Site selector state &#8211; all grey and green states can get there. </p>
<p>Moreover, these are not all the possible states of the view controller, only the UI. Internally, the view controller can be both <em>not waiting for</em> or <em>waiting for</em> data from the Stack Exchange API, including the sites list, user check data, and site icons. This isn&#8217;t even all the UI &#8211; this is just the core view (and even then, excluding each &#8220;Waiting for icon&#8221; state). The slide down user selector has it&#8217;s own internal UI state, and is activated from the two grey states in the centre of the diagram.</p>
<p>In all states other than blue, the UI is responsive to user interaction. Ideally, there would be no blue states, however in v1.0, I had no time to expand the state management to feasibly handle the feedback and changes needed to make user checking and re-association non-modal.</p>
<p>From the perspective of the API, re-association is easy. Whenever we start to track a user, the user selector dialog returns a structure obtained from the API endpoint <span style="font-family: monospace;"><a href="http://api.stackapps.com/1.0/help/method?method=users">api.sesite.example.com/1.0/users/filter?SEARCH</a></span>, (<span style="font-family: monospace;">CSUserDescription</span> from CoreStack) that indicates the user name, their identifier and an association GUID. This association identifier is unique across all accounts tied together in the Stack Exchange network. When the user toggles the selected site, if we have such an association GUID, we display a modal dialog whilst we use the <span style="font-family: monospace;"><a href="http://stackauth.com/1.0/help/method?method=users/{id}/associated">stackauth.com/1.0/users/GUID/associated</a></span> method to find all the sites this user has associated themselves with. We search this list for the newly selected site, and either fail to find it (and so disable user tracking and display an error), or we find it and update the tracking data. The modal display is then hidden.</p>
<p>So, how did I do with respect to the 3 point goals initially set above, and the more general goals set out in <a href="http://http://www.archgrove.co.uk/weblog/2010/07/27/the-development-of-six-to-eight">part one</a>?</p>
<p>As shown by the lack of solid arrows in the diagram between the two states and the first green state, the user can get a site up and running by just waiting a few seconds then pressing &#8220;Save&#8221;. This will setup the first reporting Stack Exchange site from the StackAuth API, without tracking a user. Similarly, the user is in control of the UI in all non-blue states, which represent the vast majority of interaction time with the UI. They can can cancel the setup, or change their settings. I think this &#8220;super fast initial setup&#8221; and responsive UI are key points in creating a good app.</p>
<p>The re-association feature is another subtle but important consideration for a touch based UI. We could leave it out, and whenever a user who&#8217;s tracking someone changes site, they could just re-search for their user. However, this requires more fiddly typing and network access &#8211; both best avoided on the iPhone. The StackAuth re-association API lets us save them the effort. Despite the fact that this feature is, in truth, rarely going to be used, I think the extra effort was well worth it. The fact that the Stack Exchange API allowed it with reasonable ease is testament to the quality of the feedback/design process used by the Valued Associated over at Stack Overflow Inc.</p>
<p>Now, if you&#8217;ll excuse me, I&#8217;m going to re-associate with an ale. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.archgrove.co.uk/weblog/2010/07/28/six-to-eight-development-getting-the-simple-things-right/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The development of Six to Eight</title>
		<link>http://www.archgrove.co.uk/weblog/2010/07/27/the-development-of-six-to-eight</link>
		<comments>http://www.archgrove.co.uk/weblog/2010/07/27/the-development-of-six-to-eight#comments</comments>
		<pubDate>Tue, 27 Jul 2010 09:31:31 +0000</pubDate>
		<dc:creator>Adam Wright</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[iPhone stackoverflow app sixtoeight]]></category>

		<guid isPermaLink="false">http://www.archgrove.co.uk/?p=167</guid>
		<description><![CDATA[For the last couple of months, my spare time &#8220;relaxation&#8221; programming has been the development of an iPhone app for the Stack Exchange platform. For those not in the know, Stack Exchange is an expert community presented as a Q &#038; A site. Users gather reputation for asking and answering questions. Examples you might know [...]]]></description>
			<content:encoded><![CDATA[<p>For the last couple of months, my spare time &#8220;relaxation&#8221; programming has been the development of an iPhone app for the <a href="http://stackexchange.com/">Stack Exchange platform</a>. For those not in the know, Stack Exchange is an expert community presented as a Q &#038; A site. Users gather reputation for asking and answering questions. Examples you might know are <a href="http://stackoverflow.com">Stack Overflow</a> and <a href="http://superuser.com">Super User</a> &#8211; though with the advent of <a href="http://area51.stackexchange.com/">Area 51</a>, they&#8217;re adding new sites at a fair clip.</p>
<p>They&#8217;ve recently release a <a href="http://stackapps.com">JSON based API</a> for accessing their sites, and as an avid Stack Overflow user and Apple fan, I&#8217;ve wanted a pocket client for ages. Thus, <a href="http://sixtoeightapp.com/">Six to Eight</a> was born. It&#8217;s my first &#8220;Release quality&#8221; iOS development, and I thought some people might like to know how it went &#8211; both other Stack Exchange API users, and other iPhone developers.</p>
<p>I set out to provide a good quality application. One that felt at home on my iPhone, was useful, and provided a good foundation on which I can build in the future. As such, I focused on 4 key developmental areas:</p>
<p><strong>Core functionality</strong>: It might seem obvious, but way too many apps are little more than web browsers without a decent set of browser controls. With Six to Eight, the two key ideas are &#8220;Your Stack Exchange, in your pocket&#8221; and &#8220;Your Stack Exchange user, in your pocket&#8221;. I&#8217;ve tried to design an app that provides those things in a fast and iPhone consistent experience. Everything should feel like it belongs on the iPhone &#8211; iOS like UI idioms, user input via taps, most input data being derived automatically. Users also expect a certain level of polish, which I hope I&#8217;ve delivered.</p>
<p><strong>Network error handling and recovery</strong>: Coding for the iPhone, you&#8217;ve got to be ready to handle, at any time, the loss of network connectivity or the degradation of network performance to that of a 14.4k modem. Just finished parts 1 and 2 of a critical 3 part request? You can bet on a decent number of your users losing their connection just then. Six to Eight underwent a lot of testing to ensure it remaines usable even on a GPRS connection, handles network drops gracefully, and reports them to the user as best it can.</p>
<p><strong>Asynchronous UI</strong>: Blocking your UI whilst you wait for data is a cardinal sin. It makes your app feel unresponsive, and renders it unusable on a slow connection. Six to Eight performs all data collection and processing in the background, streaming it into the UI as it arrives. This way, you get to see what&#8217;s been downloaded so far, without waiting for every request to complete. You can also cancel any request you&#8217;re bored of waiting for.</p>
<p><strong>State preservation</strong>: iPhone apps are often asked to quit with no notice, for inbound phone calls or because the user pressed &#8220;Home&#8221;. I tried to ensure that whenever you quit, both data and UI state are persisted so you reload back to the same state you left from.</p>
<p>Six to Eight is approximately 14,000 lines of code. Of course, this measure by itself is useless &#8211; but how much of this code is devoted to each part of the application is, to me, interesting. The following percentages are just my estimates based on how much time each feature took and the rough code footprint, as one can&#8217;t easily untangle the mix of the above ideas. </p>
<p><strong>Core functionality</strong>: 40%. Less than half the program is needed to provide the functionality I wanted. This includes talking to the Stack Exchange API, processing the data, presenting it in the UI and responding the UI events. If I was programming for a desktop machine with a guaranteed fast network connection, I could have basically stopped here at around 5000 lines.</p>
<p><strong>Error handling and recovery</strong>: 10%. This includes propagating errors around the system, presenting them to the user, and designing the UI so it can present partial data where missing data is in an error state.</p>
<p><strong>Asynchronous UI</strong>: 25%. This includes designing the UI as a state machine that can present data incrementally no matter what order it arrives in, as well as the concurrent download and processing of data from the Stack Exchange API.</p>
<p><strong>State preservation</strong>: 25%. This includes the ability to serialise and de-serialise all forms of Stack Exchange data and the state of each view within the UI. </p>
<p>In my next post, I&#8217;ll talk about one part of the core functionality I rather like, from both the Stack Exchange API and iPhone development perspectives.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.archgrove.co.uk/weblog/2010/07/27/the-development-of-six-to-eight/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apple (hates) Developers?</title>
		<link>http://www.archgrove.co.uk/weblog/2010/04/09/apple-hates-developers</link>
		<comments>http://www.archgrove.co.uk/weblog/2010/04/09/apple-hates-developers#comments</comments>
		<pubDate>Fri, 09 Apr 2010 17:40:54 +0000</pubDate>
		<dc:creator>Adam Wright</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.archgrove.co.uk/?p=157</guid>
		<description><![CDATA[As anyone who trawls the technology sites knows by now, Apple have as of OS 4.0 banned the use of anything other than C/++ or Objective C/++ for iPhone or iPad development. Effectively, this bans Adobe&#8217;s Flash to iPhone targeting technology, MonoTouch and several other techniques. I can think of only two (tenuously) justifiable reasons [...]]]></description>
			<content:encoded><![CDATA[<p>As anyone who trawls the technology sites knows by now, Apple have as of OS 4.0 <a href="http://daringfireball.net/2010/04/iphone_agreement_bans_flash_compiler">banned the use</a> of anything other than C/++ or Objective C/++ for iPhone or iPad development. Effectively, this bans Adobe&#8217;s Flash to iPhone targeting technology, MonoTouch and several other techniques. I can think of only two (tenuously) justifiable reasons for this.</p>
<ol>
<li>Perhaps, during the beta, they want code written in C (and derivatives) to aid in debugging framework bugs. Rather than &#8220;My App doesn&#8217;t WORK!!!!! (Using MonoTouch Vxxyy)&#8221;, they can get a repro using a stack they know and control top to bottom. In this case, I can see it as justified.</li>
<li>If it&#8217;s specifically to target cross-compilers as a business decision, to ensure that iPhone only gets &#8220;exclusives&#8221;, then I suppose it&#8217;s their prerogative. It will probably backfire long-term, as their market share isn&#8217;t that dominant. &#8220;Browser, Palm, Android + all else&#8221; or &#8220;iPhone&#8221; makes the iPhone a secondary port target versus a first class platform.</li>
</ol>
<p>Gruber <a href="http://daringfireball.net/2010/04/why_apple_changed_section_331">gives a third</a>, pretty sensible conclusion &#8211; that they just don&#8217;t want to hand control of their platform to another vendor, and become a commodity target &#8211; just another checkbox inside Flash alongside &#8220;Web&#8221; and &#8220;Android&#8221;. If developers started using these meta development tools, all of the iPhones advantages vanish &#8211; it&#8217;s just another smartphone that runs Flash based applications.</p>
<p>For Apple the platform holder, this makes sense. For developers, any of the reasons are overly restrictive. This is, at best, ethically dubious without inconveniencing real development (which is all going on in Objective C already). At worst, it&#8217;s indicative of an ongoing schizophrenic pathology within Apple management where, despite winning ongoing customers through applications, they are happy to slap developers around just to see how far they can go before everyone decamps to Android.</p>
<p>We already exist with the capricious Application Review policy whereby you&#8217;re playing Russian Roulette with your development time &#8211; there&#8217;s no way to know that tell which perfectly innocent development choice will lead to rejection. Add this new restriction, and one has to wonder what choice made today will be retrospectively banned tomorrow. It&#8217;s an odd strategy, as there are plenty of innovative developers who are now scared of targeting the platform, whilst coding sweat shops keep flooding the channel with $0.10 an hour developer dross; developers who will use whatever they&#8217;re paid to use, be it Objective C or Flash. Pump enough stuff in, and some of it leaks through.</p>
<p>I can take two solaces from this personally. First, it  literally can&#8217;t ever sensibly apply to OS X &#8211; the historical baggage makes this kind of restrictive move possible only on the closed and dominant iPhone platform. Even if they ever decided to make a &#8220;Mac App Store&#8221;, there would always have to be a standard development path lest they lose the thousands of platform portable apps that they current have (and really, OS X is still missing large swathes of desktop software that Windows has). Second, it makes my Objective C skills more valuable.</p>
<p>I still think it&#8217;s a poor move technically and ethically, but the iPhone platform has always been rife with these land-mines. Whether it turns out to be a good move from a business perspective, the market and time will tell.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.archgrove.co.uk/weblog/2010/04/09/apple-hates-developers/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A few notes on Windows Phone 7 Development comparisons</title>
		<link>http://www.archgrove.co.uk/weblog/2010/04/01/a-few-notes-on-windows-phone-7-dev</link>
		<comments>http://www.archgrove.co.uk/weblog/2010/04/01/a-few-notes-on-windows-phone-7-dev#comments</comments>
		<pubDate>Thu, 01 Apr 2010 13:28:33 +0000</pubDate>
		<dc:creator>Adam Wright</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.archgrove.co.uk/weblog/2010/04/01/a-few-notes-on-windows-phone-7-dev</guid>
		<description><![CDATA[Iâ€™ve exchanged a few e-mails with Shawn Burke, whoâ€™s writing the â€œiPhone SDK vs. Windows Phone 7 Series SDK Challengeâ€ series on his blog (which I highly recommend you read). Those reading my previous posts will know Iâ€™ve taken him to task for a few of his comments concerning the â€œnumber of linesâ€ comparison between [...]]]></description>
			<content:encoded><![CDATA[<p>Iâ€™ve exchanged a few e-mails with Shawn Burke, whoâ€™s writing the â€œiPhone SDK vs. Windows Phone 7 Series SDK Challengeâ€ series on his <a href="http://blogs.msdn.com/sburke/">blog</a> (which I highly recommend you read). Those reading my <a href="http://www.archgrove.co.uk/weblog/2010/03/25/104">previous</a> <a href="http://www.archgrove.co.uk/weblog/2010/03/31/a-response-to-part-2-iphone-vs-windows-phone-7-challenge">posts</a> will know Iâ€™ve taken him to task for a few of his comments concerning the â€œnumber of linesâ€ comparison between the iPhone and WP7. I just want to clarify a couple of my comments &#8211; not at his request, just to set the record straight. </p>
<p>I mentioned that Expression Blend is not a free product, but heâ€™s mentions that â€œA basic version of the tooling for WP7 (including Blend) will always be freeâ€, which is good news &#8211; the XAML designer in Visual Studio frankly sucks, and having to pay for a UI designer would be unwelcome. The main point of our brief exchange has been the (lack of) quality of Appleâ€™s documentation, which I entirely agree with. The Interface Builder techniques I used in my implementations are not widely known, being documented in an obscure corner of the IB Manual, and itâ€™s understandable that someone just arriving on the platform would think they didnâ€™t exist. Itâ€™s also undeniably true that the iPhone tutorials are more  complex than they need be to achieve the target application.</p>
<p>To clarify my opinion on this, I believe the tutorials are not going for the â€œidealâ€ MoveMe application &#8211; theyâ€™re covering a gamut of techniques people will need whilst developing for iPhone. Is the pacing of the tutorials quite right? Would a more â€œdrag and dropâ€ IB approach in the first few be preferable? I donâ€™t know. Given the number of applications in the App Store, it certainly seems most people are getting to grips with iPhone development. Though given the quality of most of them, itâ€™s fair to say thereâ€™s scope for improvement.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.archgrove.co.uk/weblog/2010/04/01/a-few-notes-on-windows-phone-7-dev/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A response to Part 2 of the &#8220;iPhone vs Windows Phone 7 Challenge&#8221;</title>
		<link>http://www.archgrove.co.uk/weblog/2010/03/31/a-response-to-part-2-iphone-vs-windows-phone-7-challenge</link>
		<comments>http://www.archgrove.co.uk/weblog/2010/03/31/a-response-to-part-2-iphone-vs-windows-phone-7-challenge#comments</comments>
		<pubDate>Wed, 31 Mar 2010 18:05:19 +0000</pubDate>
		<dc:creator>Adam Wright</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.archgrove.co.uk/?p=119</guid>
		<description><![CDATA[Readers of my previous post will recall that I&#8217;ve been following along with Shawn Burke&#8217;s posts as he explores porting Apple&#8217;s iPhone Development Tutorials to the Windows Phone 7 development environment. We previously examined his look at the &#8220;Hello World&#8221; example, showing that despite the claims, it&#8217;s just as easy on iPhone as WP7. Here, [...]]]></description>
			<content:encoded><![CDATA[<p>Readers of my <a href="http://www.archgrove.co.uk/weblog/2010/03/25/104">previous post</a> will recall that I&#8217;ve been following along with <a href="http://blogs.msdn.com/sburke">Shawn Burke&#8217;s posts</a> as he explores porting Apple&#8217;s iPhone Development Tutorials to the Windows Phone 7 development environment. We previously examined his look at the &#8220;Hello World&#8221; example, showing that despite the claims, it&#8217;s just as easy on iPhone as WP7. Here, we explore the <a href="http://blogs.msdn.com/sburke/archive/2010/03/27/iphone-sdk-vs-windows-phone-7-series-sdk-challenge-part-2-moveme.aspx">second in the series</a>: the &#8220;Move Me&#8221; example. I doubt I&#8217;ll do this for every post, but so far, it&#8217;s been an interesting couple of hours.</p>
<p>As before, the example rather falls over by being a comparison of &#8220;iPhone Best Practice Tutorial&#8221; versus &#8220;Ad-hoc implementation&#8221;. As I mentioned previously, the Apple tutorial series are designed to showcase development concepts, not necessarily the fastest way to achieve the goal of the sample application. This should not be read as saying the post is bad &#8211; it&#8217;s an interesting comparison in the differing development philosophy of WP7, wherein the majority of MoveMe can be created declaratively in XAML. Cocoa doesn&#8217;t have a similar UI DSL, and one can&#8217;t deny the power of the Blend/WPF combination; it made the example trivial. It is, however, probably fair to point out that Expression Blend is <em>not</em> part of Visual Studio (RRP $599), and that UIKit, Interface Builder and Core Animation make this specific task pretty simple on the iPhone as well. </p>
<p>It&#8217;s claimed that WP7 needs 5 (6 with a correction), versus more than 100 for the iPhone. We&#8217;re not going to beat 6 (typed) lines of code, but we can do a lot better than the claimed 100. By using a custom UIButton configured in Interface Builder along with Core Animation&#8217;s implicit property animations, we can achieve the result in 20 lines &#8211; with most of the work going into building the bounce animation. If we didn&#8217;t want the bounce, 8 lines would do the job. In the following, the only typed lines were the bodies of the functions and the #import statement for QuartzCore. Interface Builder generated the event handler stubs, instance variables and hooked up all the events for us. </p>
<pre name="code" class="c">
#import &lt;QuartzCore /QuartzCore.h&gt;
#import "MoveMeViewController.h"

@implementation moveMeViewController

- (IBAction)touchDown:(id)sender {
    [UIView beginAnimations:@"scale" context:nil];
    button.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.1f, 1.1f);
    [UIView commitAnimations];
}

- (IBAction)touchUp:(id)sender {
    CAKeyframeAnimation *bounceAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];

    CGMutablePathRef thePath = CGPathCreateMutable();
    CGPathMoveToPoint(thePath, NULL, button.center.x, button.center.y);

    int overrun = 10;
    CGPoint pos = button.center;

    while (overrun--) {
        pos.x = [self view].center.x + (overrun % 2  ? 1 : -1) * (pos.x - [self view].center.x) * overrun / 10.0;
        pos.y = [self view].center.y + (overrun % 2  ? 1 : -1) * (pos.y - [self view].center.y) * overrun / 10.0;

        CGPathAddLineToPoint(thePath, NULL, pos.x, pos.y);
	}

    bounceAnimation.path = thePath;
    bounceAnimation.duration = 1.5;

    CGPathRelease(thePath);

    [UIView beginAnimations:@"scale" context:nil];
    button.transform = CGAffineTransformIdentity;
    [[button layer] addAnimation:bounceAnimation forKey:nil];
    [UIView commitAnimations];

    button.center = [self view].center;
}

- (IBAction)touchDrag:(UIControl*)c withEvent:(UIEvent*)event {
    button.center = [[[event allTouches] anyObject] locationInView:nil];
}

@end
</pre>
<p>The WP7 development magic here is really in Expression Blend &#8211; creating the XAML by hand would be around 60 lines of XML. I&#8217;m not a XAML expert, but examining the provided code, there&#8217;s no specific entry for &#8220;Bounce&#8221; &#8211; the effect seems to be being created by a combination of translations and easing functions. Creating it by hand would, I&#8217;d wager, be pretty tough &#8211; as hard as it was for me to write the above simple code. Therefore, what we really lack on the iPhone side is a tool or version of Interface Builder that obviates the need for the &#8220;bounce&#8221; code above. Of course, the code hacked together for the above could be factored into a category on UIView (similar to .net Extension methods) that adds  &#8220;Animate with fancy effects&#8221; method. We could then, on any UIView, call something like</p>
<pre name="code" class="c">
  [button addAnimationFromPoint:a toPoint:b withEffect:BounceEffect];
</pre>
<p>So, again, the developmental legwork difference for this example isn&#8217;t as large as was suggested. To specifically correct the list of concepts that one needs to code by hand on the iPhone:</p>
<ol>
<li><del>Drawing Images</del>: No need, Interface Builder will set this up for us.</li>
<li><del>Drawing Text</del>: Again, handled by IB.</li>
<li><del>Handling touch events</del>: Nope, both created and hooked up via IB.</li>
<li>Creating animations: Yes, we need to indicate we want animations in the code.</li>
<li><del>Scaling animations</del>: No &#8211; comes for free with CA&#8217;s implicit animation system.</li>
<li>Building a path and animating along that: Yes, and this is a pain in the neck.</li>
</ol>
<p>I suppose it&#8217;s hard to argue that in some sense, the WP7 development was not &#8220;easier&#8221;, certainly for a novice or graphical designer. For an experienced developer, especially one who writes suitably reusable code, I&#8217;d argue that it&#8217;s pretty much a wash.</p>
<p>Edit: Dear me, I&#8217;m truly awful at missing &#8220;not&#8221; from my writing &#8211; For those who read the previous version, let me make it clear I was not saying the post was bad, nor was I saying the WP7 development was harder than the iPhone.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.archgrove.co.uk/weblog/2010/03/31/a-response-to-part-2-iphone-vs-windows-phone-7-challenge/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Responding to the &#8220;iPhone SDK vs Windows Phone 7 Series SDK Challenge&#8221;</title>
		<link>http://www.archgrove.co.uk/weblog/2010/03/25/104</link>
		<comments>http://www.archgrove.co.uk/weblog/2010/03/25/104#comments</comments>
		<pubDate>Thu, 25 Mar 2010 19:53:25 +0000</pubDate>
		<dc:creator>Adam Wright</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.archgrove.co.uk/weblog/2010/03/25/104</guid>
		<description><![CDATA[Over at his blog, Shawn Burke is running a series on &#8220;iPhone SDK vs Windows Phone 7 Series SDK Challenge&#8221;. He takes examples from Apple&#8217;s iPhone SDK, and shows how to create them using the Windows Phone 7 SDK, taking care to crow about supposed advantages of the Microsoft approach. In this post, I figured [...]]]></description>
			<content:encoded><![CDATA[<p>Over at his <a href="http://blogs.msdn.com/sburke/archive/2010/03/23/iphone-sdk-vs-windows-phone-7-series-sdk-challenge-part-1-hello-world.aspx">blog</a>, Shawn Burke is running a series on &#8220;iPhone SDK vs Windows Phone 7 Series SDK Challenge&#8221;. He takes examples from Apple&#8217;s iPhone SDK, and shows how to create them using the Windows Phone 7 SDK, taking care to crow about supposed advantages of the Microsoft approach. In this post, I figured I&#8217;d examine his first &#8220;Hello World&#8221; example, and see how accurate the result is.</p>
<p>Note beforehand that I&#8217;m not disputing the power of WPF and C#. Given the choice of C# of Objective C, I&#8217;d probably rather work with C#. However, these types of language/API comparisons are rarely useful, nearly always mistaken, and correcting the record seemed an interesting task.</p>
<p>The first problem is that the title is inaccurate &#8211; it&#8217;s &#8220;iPhone SDK Hello World Tutorial vs ad-hoc implementation in WP7 SDK&#8221;. To show this, he goes through the tutorial and shows the same result prepared in WP7, with the banner claim being &#8220;4 lines of Code for Windows Phone 7, 44 for iPhone&#8221;. This is, at best, disingenuous. In the following video, I make the iPhone &#8220;Hello World&#8221; application using exactly the same number of typed lines of code as Shawn&#8217;s blog post. It&#8217;s not monumentally fascinating, but might show some Interface Builder features that are not widely known.</p>
<p><object width="640" height="505"><param name="movie" value="http://www.youtube.com/v/uyRni02DsUI&#038;hl=en_GB&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/uyRni02DsUI&#038;hl=en_GB&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="505"></embed></object></p>
<p>He makes two other points I&#8217;ll call out before exploring why he might make these mistakes.</p>
<p><em>&#8220;I was surprised that the User Interface Designer in XCode doesn&#8217;t automatically create instance variables for me and wire them up to the corresponding elements&#8221;<br />
</em></p>
<p>As shown, you can have Interface Builder create instance variables you need them. Regarding the automatic generation of instance variables, this is, I suppose, a matter of opinion &#8211; but years of Windows Forms programming has taught me that automated generation of instance variables for all UI elements is a nightmare. Your namespace is cluttered with dozens of instances you never need to reference and just add noise to your code.</p>
<p><em>&#8220;10% of the code, 1 file instead of 4, it&#8217;s just much simpler&#8221;</em></p>
<p>As shown, the amount of code you have to write it identical. 1 file instead of 4 is just wrong &#8211; if you download his sample program, there are 2 XAML files and 2 C# files. Counting the NIB file and main.m files as part of the iPhone solution, there are 6. So it&#8217;s 4 vs 6 in terms of files in the project, but identical in terms of the number of files you need to edit (1 XAML and C# vs 1 NIB and M file).</p>
<p><strong>Why make the errors?</strong></p>
<p>Shawn based his comparison on the Apple Tutorial. Why doesn&#8217;t the iPhone &#8220;Hello World&#8221; tutorial do it my way? Because Apple tutorials teach you the &#8220;Apple way&#8221; of development; &#8220;Best practice iPhone development&#8221;, if you will. Cocoa is, for better or worse, as much a philosophy as an API. If you don&#8217;t buy into the MVC approach, if you don&#8217;t structure your code in a Cocoa friendly way, you&#8217;ll be able to develop &#8211; but you&#8217;ll find it painful. As in it&#8217;s products, Apple tries to guide developers into the &#8220;right&#8221; mindset. Therefore, a fairer comparison would have been &#8220;iPhone Hello World vs Best practice WP7 Hello World&#8221;.</p>
<p>This is not to say there aren&#8217;t real missing features from the iPhone development environment compared to the new Windows 7 setup. Largely, this is down to Apple being conservative with the runtime features they provide for the iPhone OS. Partially, they&#8217;re feeling their way as they go. More importantly, they&#8217;ve been working on relatively limited hardware. The latest iPhone OS still supports the original iPhone, which had only a 412Mhz ARM CPU with 128Mb of RAM. Windows 7 will mandate a minimum of an ARMv7 Cortex/Scorpion with 256Mb RAM, giving the OS and application runtime a minimum of twice the memory and compute resource to play with.</p>
<p>If we compare against Cocoa/Objective C for OS 10.6, we see a lot of features that are waiting to be ported to the iPhone: Blocks (i.e. lambda functions for C), garbage collection, and API improvements. Given the ever progressing iPhone hardware (and new iPad), I&#8217;m expecting these shiny developer tools for iPhone 4.0 &#8211; personally, I&#8217;m voting for blocks, though a lot of people would prefer garbage collection). I&#8217;m also expecting Apple to keep forward porting Application Kit features that are currently missing &#8211; Cocoa bindings being the big one. With these, Interface Builder for OS X can build the &#8220;Hello World&#8221; desktop app without ever writing a single line of code (in fact, by typing only &#8220;Hello World&#8221; and &#8220;Hello&#8221; at the keyboard).</p>
<p>As a cross platform developer, I&#8217;ll continue reading the series with interest. I do hope, however, for rather fairer comparisons in the future.</p>
<p>EDIT: Woops, first version claimed there are, in fact, no missing features in iPhone development. Now clear that I&#8217;m not under RDF influence.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.archgrove.co.uk/weblog/2010/03/25/104/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>A route to the past: Magellan 2 (Part III)</title>
		<link>http://www.archgrove.co.uk/weblog/2007/06/01/a-route-to-the-past-magellan-2-part-iii</link>
		<comments>http://www.archgrove.co.uk/weblog/2007/06/01/a-route-to-the-past-magellan-2-part-iii#comments</comments>
		<pubDate>Fri, 01 Jun 2007 18:58:26 +0000</pubDate>
		<dc:creator>Adam Wright</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.archgrove.co.uk/?p=75</guid>
		<description><![CDATA[Right, we left off (a long while ago), having looked at the basic dungeon layout. The question was, how do we turn the geometry of a dungeon cell into a two dimensional map? Let’s look at a (badly, hand) drawn section of a dungeon wall. It’s got a floor, some obvious wall, and a little [...]]]></description>
			<content:encoded><![CDATA[<p>Right, we left off (a long while ago), having looked at the basic dungeon layout. The question was, how do we turn the geometry of a dungeon cell into a two dimensional map? Let’s look at a (badly, hand) drawn section of a dungeon wall. It’s got a floor, some obvious wall, and a little “hump” – some kind of rock, or bizarre architectural anomaly (it is a dungeon, after all). </p>
<p>
<img src="/wp-content/m2_allLines.png" alt="Vector art image of dungeon geometry" />
</p>
<p>We can see the raw triangles in 3D, and we’d like to get this down to a set of lines in 2D (we can draw lines very easily using the APIs available to us). To accomplish our goal, we’ll need to think about what we actually want to see on the map – showing the floor, and little lumps and bumps is not really useful information for people. The only real obstructions that they’ll want to see mapped are the extents of the dungeon – the walls.</p>
<p>How can we distinguish a wall from the geometry? Well, the distinguishing fact I used in my simple algorithm was that it’s vertical – everything within a certain tolerance of the vertical axis is a “wall”, and would appear on the map.</p>
<p>On this diagram, we see the tolerance region – all polygons that are upright enough to be contained within the triangle are going on the map. Let’s remove everything that’s outside the verticality acceptance region, and see what we’ve got left.</p>
<p>
<img src="/wp-content/m2_allLinesWithGuide.png" alt="Tolerance region for wall verticality" />
</p>
<p>Not bad – everything remaining looks pretty damn wall like to me. All we’ve now to do is turn this into a set of lines, discard the vertical components, and we have a reasonable 2D representation of the dungeon block we can use to map.</p>
<p>
  <img src="/wp-content/m2_allLinesSomeRemoved.png" alt="The final wall geometry" />
</p>
<p>That’s pretty much it for Magellan 2 – once these line blocks are collected, they’re simply transformed (by some simple mathematics) to deal with the translation and rotation of the dungeon relative to the current viewpoint of your character. Rendering them to the screen is just a case of taking each line, transforming it, and then telling Decal “draw this line starting here and ending here”.</p>
<p>There are plenty of problems with this approach (some of which manifested themselves in the released version); however, this explains the basic concept (which was all I set out to do). One day, if there’s interest, I might write about these design faults, and the potential improvements that could be made.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.archgrove.co.uk/weblog/2007/06/01/a-route-to-the-past-magellan-2-part-iii/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A route to the past: Magellan 2 (Part II)</title>
		<link>http://www.archgrove.co.uk/weblog/2007/04/11/a-route-to-the-past-magellan-2-part-ii</link>
		<comments>http://www.archgrove.co.uk/weblog/2007/04/11/a-route-to-the-past-magellan-2-part-ii#comments</comments>
		<pubDate>Wed, 11 Apr 2007 10:29:32 +0000</pubDate>
		<dc:creator>Adam Wright</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.archgrove.co.uk/?p=74</guid>
		<description><![CDATA[Just to clear up some misconceptions, the point of this article is not to recreate the plugin, or repair it for the modern Asheron’s Call. The plan is to write a set of articles on how it was created, and why it (in general) worked. Those looking for a replacement would do well to visit [...]]]></description>
			<content:encoded><![CDATA[<p>Just to clear up some misconceptions, the point of this article is not to recreate the plugin, or repair it for the modern Asheron’s Call. The plan is to write a set of articles on how it was created, and why it (in general) worked. Those looking for a replacement would do well to visit <a href="http://www.flynn1179.me.uk/ac/?minimap">http://www.flynn1179.me.uk/ac/?minimap</a> and see the impressive looking work that Thorfinn Sigurdssen has been doing (Disclaimer: I have neither personally tested this, nor been contacted by the author).</p>
<p>Last time, we left off having made a series of educated guesses about how the dungeon system in AC works. From our observations, we’ve noted that every dungeon seems to be laid out in a giant 3d grid of cubes – assembled as if from lego bricks, prefabricated elements of dungeon. </p>
<p><img src='/wp-content/dungeonCubes.png' alt='AC Dungeon template' /></p>
<p>We can see the prototypical dungeon template above – each little cube is ready to be filled with a one of a choice of dungeon blocks by an eager designer. A template block might look as follows.</p>
<p><img src='/wp-content/cave.jpg' alt='AC2 Dungeon cell' /></p>
<p>This one is taken from my Asherons’s Call 2 archives (so don’t go looking for it in game), but it illustrates the point. The player walks around on the interior (the complex looking set of triangles), and the rest of the cube is filled with virtual nothingness – in this fashion, we can make our big cubes look like caves, temples, whatever is needed (rather than a boring apartment block).</p>
<p>We could take four of the above dungeon elements (that we call dungeon cells), rotate them around and put them into adjoining cubes in the template to create a donut dungeon – a giant loop. Obviously, it’s up to the designer to ensure that there’s no corridor or tunnel that leads into an unfilled cube (and hence into the void).</p>
<p>This is all well and good, but now that we’ve made a plausible (and in this case, rather educated) guess at the dungeon structure, how does it help us? Our task is to draw a map of the walls of the dungeon, not big wireframe meshes stuck around the place! So, tune in next time to see a little bit of simple mathematics that will transform the above into something more useful for our purposes.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.archgrove.co.uk/weblog/2007/04/11/a-route-to-the-past-magellan-2-part-ii/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A route to the past: Magellan 2</title>
		<link>http://www.archgrove.co.uk/weblog/2007/03/27/a-route-to-the-past-magellan-2</link>
		<comments>http://www.archgrove.co.uk/weblog/2007/03/27/a-route-to-the-past-magellan-2#comments</comments>
		<pubDate>Tue, 27 Mar 2007 19:38:11 +0000</pubDate>
		<dc:creator>Adam Wright</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.archgrove.co.uk/?p=73</guid>
		<description><![CDATA[It&#8217;s been a long time since I posted anything here, but as I only write when I have both time and something to say, it&#8217;s not that surprising. I&#8217;m moved to put fingers to keyboard today to discuss something I still get regular e-mails about &#8211; an old Decal plug-in, Magellan 2, for Asheron&#8217;s Call [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a long time since I posted anything here, but as I only write when I have both time and something to say, it&#8217;s not that surprising. I&#8217;m moved to put fingers to keyboard today to discuss something I still get regular e-mails about &#8211; an old Decal plug-in, Magellan 2, for Asheron&#8217;s Call (for those who don&#8217;t recognise these terms, an <a href="/series/reapplying-the-decal/">older article series</a> might be interesting).</p>
<p>The main function of Magellan 2 was as a dungeon mapping system &#8211; it would automatically generate real-time wireframe overviews of any dungeon as you walked around it. There&#8217;s nothing particularly amazing about it; indeed, retrospectively, a lot of how it worked was naive at best and bad at worst. However, a lot of people seemed to like it, and I still get about an email a fortnight asking for source code &#038; technical information. So far, I&#8217;ve been sending out the code about once every 3 months, to give each person a chance to repair the code and publish something, alas to no avail. Hence, I figure it&#8217;s time to publish something more general and see what people can create.</p>
<p><img src='/wp-content/articleShot.jpg' alt='Magellan 2 mapping screenshot' /></p>
<p>Now, Magellan 2 did more than just map dungeons but the additional functionality (place search etc) is pretty trivial data management and nothing we&#8217;re interested in. We&#8217;ll be focusing on the map generation, but I&#8217;m not going to write this as a detailed set of technical specifications &#8211; more as a journey of creation suitable for all who are interested. Hopefully the information contained within, plus additional downloadable material will give people everything they need to recreate the work, if they want to.</p>
<p><strong>Phase One : The problem</strong></p>
<p><em>What we want</em>: To create a client integrated real time usable map display of any dungeon a player wanders into, something that will help them both find their way around and allow them to explore the full depth of the dungeon (no more missed turns!).</p>
<p><em>What we we know</em>: We have two data files, &#8220;cell.dat&#8221; and &#8220;portal.dat&#8221;, which form an archive of many thousands of smaller files. We also have some vague idea of how the AC client software deals with the problem &#8211; we know that when we enter a new dungeon, some data is downloaded and the &#8220;cell.dat&#8221; file gets larger. We also know, from our many years of dungeon crawling, that dungeons are very &#8220;modular&#8221; in design &#8211; they seem to be built out of standard components, reused many times within the dungeons. </p>
<p><em>What we can do</em>: We can read the files contained in the cell.dat and portal.dat archive files. We can also, via Decal, draw onto the players screen, and find out their location and orientation in the world.</p>
<p>The challenge is set! Over the next few articles, we&#8217;ll see what we can create.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.archgrove.co.uk/weblog/2007/03/27/a-route-to-the-past-magellan-2/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Continued (2): Simple concurrent evaluation strategies in mainstream languages</title>
		<link>http://www.archgrove.co.uk/weblog/2006/08/08/continued-2-simple-concurrent-evaluation-strategies-in-mainstream-languages</link>
		<comments>http://www.archgrove.co.uk/weblog/2006/08/08/continued-2-simple-concurrent-evaluation-strategies-in-mainstream-languages#comments</comments>
		<pubDate>Tue, 08 Aug 2006 14:35:56 +0000</pubDate>
		<dc:creator>Adam Wright</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Computer Science]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.archgrove.co.uk/weblog/2006/08/08/continued-2-simple-concurrent-evaluation-strategies-in-mainstream-languages</guid>
		<description><![CDATA[OK, so we’ve all been busily tapping away at our keyboards trying to implement the rough design we came up with last time. Let’s have a look at one way of doing it (this is just one way; there are obviously many different methods). public class CallByFuture&#60;T&#62; { public delegate T CallResult(); public static implicit [...]]]></description>
			<content:encoded><![CDATA[<p>OK, so we’ve all been busily tapping away at our keyboards trying to implement the rough design we came up with <a href="/weblog/2006/08/03/continued-simple-concurrent-evaluation-strategies-in-mainstream-languages">last time</a>. Let’s have a look at one way of doing it (this is just one way; there are obviously many different methods).</p>
<pre>
    public class CallByFuture&lt;T&gt;
    {
        public delegate T CallResult();

        public static implicit operator T(CallByFuture&lt;T&gt; instance)
        {
            return instance.Result();
        }

        public static T operator ~(CallByFuture&lt;T&gt; instance)
        {
            return instance.Result();
        }

        private System.Threading.Thread workerThread;
        private T result;

        public CallByFuture(CallResult func)
        {
            workerThread = new System.Threading.Thread(delegate(object state) {
                ((CallByFuture&lt;T&gt;)state).result = func();
            });

            workerThread.Start(this);
        }

        public T Result()
        {
            workerThread.Join();

            return result;
        }
    }
</pre>
<p>The implementation has tried to stay as close to the design goals as possible; we have a generic class, parameterised by the return type of a delegate which the user will create (either implicitly through an existing function, or explicitly with an anonymous method). The construction spins up a thread which evaluates this delegate, and gives the result back to the enclosing CallByFuture class to be made public via a Result method which will block until the answer is available. For syntactic sugar, we allow the unary bitwise NOT operator as a shortcut to the Result method (so rather than a call to the result type T expressed by the CallByFuture being <i>t.Result().Foo</i>, we have simply <i>(~t).Blah</i>.</p>
<p>The use of <i>operator~</i> as an “easy conversion” might seem rather strange – after all, the language supports explicit type conversion operators natively. It does not, however, support having both an implicit and explicit conversion operators for the same type; the people who actually read the code will have noticed the implicit conversion snuck in at the top of the class.</p>
<p>The implicit conversion is very useful – it allows you to use a CallByFuture<t> in most cases you want a T without any additional syntax. However. I would personally probably flag its inclusion as “controversial ” in a code review mainly due to the excessive “magic” behind the conversion of complex types – an innocuous usage of a variable might entail a complex evaluation behind the scene (rather than the virtual no-op of just reference passing you were expecting) – it might even throw an exception. In our case, the worst that can happen is that it must wait until the result is evaluated (any exceptions will be thrown on the CallByFuture thread, and we’ll discuss them later). Total worst case, the evaluation locks because the CallByFuture delegate never completes.</p>
<p>Our implementation rules stated we wanted something we could “drop in” to existing programs, and the implicit conversion certainly aids in that so next time, we’ll look at mitigating the problems it raises as well as some usage examples to prove this really does work.</p>
<p>[Edit: Woops - forgot to actually include <i>operator~</i>]</t></p>
]]></content:encoded>
			<wfw:commentRss>http://www.archgrove.co.uk/weblog/2006/08/08/continued-2-simple-concurrent-evaluation-strategies-in-mainstream-languages/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
