<?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>{(something&#124;&#124;other).soft()} &#187; Development</title>
	<atom:link href="http://www.somethingorothersoft.com/category/development/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.somethingorothersoft.com</link>
	<description>About Software Development And Other Stuff By Igor Zevaka</description>
	<lastBuildDate>Mon, 25 Jul 2011 00:03:47 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Git Rebase &#8211; more than a machine gun to shoot yourself in the foot with</title>
		<link>http://www.somethingorothersoft.com/2011/04/11/git-rebase-more-than-a-machine-gun-to-shoot-yourself-in-the-foot-with/</link>
		<comments>http://www.somethingorothersoft.com/2011/04/11/git-rebase-more-than-a-machine-gun-to-shoot-yourself-in-the-foot-with/#comments</comments>
		<pubDate>Sun, 10 Apr 2011 23:16:42 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/2011/04/11/git-rebase-more-than-a-machine-gun-to-shoot-yourself-in-the-foot-with/</guid>
		<description><![CDATA[There is an adage in the development circles that C programming language is both powerful and dangerous, akin to a gun that you can accidentally shoot yourself in the foot with. By the same token, C++ makes it possibly to blow your entire leg. In this post i would like to apply these analogies in the context of git version control system.]]></description>
			<content:encoded><![CDATA[<p>There is an adage in the development circles that C programming language is both powerful and dangerous, akin to a gun that you can accidentally shoot yourself in the foot with. By the same token, C++ makes it possibly to blow your entire leg. In this post i would like to apply these analogies in the context of git version control system.</p>

<p>The actual quote about c and C++ is most commonly attributed to Bjarne Stroustrup and it goes like this:</p>

<blockquote>
  <p>C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off (<a href="http://www2.research.att.com/~bs/bs_faq.html#really-say-that">link</a>)</p>
</blockquote>

<p>git is not for faint hearted. Proper usage requires knowledge of branches, merging, remotes, detached heads (OK, maybe not detached heads, but I just wanted to mention those as they sound cool). Plenty a developer can go for years without ever having to branch (myself included). git, on the other hand almost mandates using local branches on daily basis.</p>

<p>History rewriting deserves a special chapter in the book of git-fu. The fetch-rebase-rebase workflow is ostensibly simple, yet incredibly powerful. This lead me to believe that git-rebase is a special kind of weapon &#8211; a handheld Tomahawk launcher with a twist. 
<a href="http://www.somethingorothersoft.com/wp-content/uploads/2011/04/300px-Tomahawk_Block_IV_cruise_missile_-crop.jpg"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2011/04/300px-Tomahawk_Block_IV_cruise_missile_-crop.jpg" alt="" title="300px-Tomahawk_Block_IV_cruise_missile_-crop" width="300" height="193" class="alignnone size-full wp-image-526" /></a><br />
If you do happen to shoot yourself in the foot, and by that stage you already took out half a suburb with you, it gives you an option to go back in time and prevent yourself from doing that. A bit like Nicholas Cage in the movie <a href="http://www.imdb.com/title/tt0435705/">Next</a>.</p>

<p>The only catch is that you get a second chance once, rewriting history is something that should only be on on un-pushed changes. Once you push those changes (and you get a safeguard from that git that will disallow pushing rewritten history without <code>--force</code> flag), all bets are off. I am not even sure what happens with other people&#8217;s repositories when a branch has been rebased upstream, most likely your coworkers will be highly pissed of with you.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2011/04/11/git-rebase-more-than-a-machine-gun-to-shoot-yourself-in-the-foot-with/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How Path to Happiness Is, Surprisingly, Doing What You Love (and StackOverflow)</title>
		<link>http://www.somethingorothersoft.com/2011/02/23/how-path-to-happiness-is-surprisingly-doing-what-you-love-and-stackoverflow/</link>
		<comments>http://www.somethingorothersoft.com/2011/02/23/how-path-to-happiness-is-surprisingly-doing-what-you-love-and-stackoverflow/#comments</comments>
		<pubDate>Wed, 23 Feb 2011 12:24:11 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[employment]]></category>
		<category><![CDATA[interviews]]></category>
		<category><![CDATA[stackoverflow]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=513</guid>
		<description><![CDATA[Reflection on the path I've taken to find a new (totally awesome) job.]]></description>
			<content:encoded><![CDATA[<p>This is really just a bit of reflection on the path I&#8217;ve taken to find a new (totally awesome) job. There are a number of things I&#8217;ve found and I would like to share those with you.</p>

<h3>Development managers have beards</h3>

<p>Seriously. 100% of the dev managers that I&#8217;ve come across (a total of two) have beards. With that, I would like to conclude that all development managers have beards. Also, both of the ones I met happen to be really cool dudes, but that&#8217;s beside the point.</p>

<p>Having said that, I realise my failing to secure a development manager position. I didn&#8217;t have a beard. So, if you are on the market for dev manager position, you <strong>must</strong> have a beard.</p>

<h3>It helps to be good</h3>

<p>I really enjoyed going to the interviews and I thought I did alright at all of them. So much so, that I thought I could totally do it full time. At some point I realised that it&#8217;s not some weird skill that I happened to have, but that I was pretty good at what I do. Not totally awsome, which is the goal, but better than average.</p>

<p>Don&#8217;t take this the wrong way. If you are reading this post, I can pretty much guarantee that I am on par with you &#8211; just a normal programmer who is pretty passionate about what he does. I&#8217;ve met plenty of totally awsome devs in my time and I can tell you, I&#8217;d give an arm and leg to be half as awesome as them. It is pretty surprising, really, how little effort it takes to be above the average line in this business.</p>

<h3>Karma is totally real</h3>

<p>Being a fairly active StackOverflow participant, giving back to the community is fun. You get points and get to receive instant feedback from others if something that you say sucks. To most non-geek folk out there it&#8217;s virtually impossible to explain why you would selflessly spend so much of your time helping others.</p>

<p>But get this. After two months of constant applying and weeks of interviews, technical tests and take home assignments (which are totally what you&#8217;d get if you are going for senior developer positions), the <em>one</em> offer I got was through agent thrawling SO for people in the area that are active in a particular tag set.</p>

<p>Not by placing a job ad on careers.</p>

<p>Not by signing to search candidates on careers.</p>

<p>Just by brute forcing their way through participants. Kudos.</p>

<h3>You have to work hard for it</h3>

<p>Yeah. Applying for senior developer position in Sydney is hard work. The market for .NET developers is pretty lively at the moment, so I would recommend to only apply for the jobs that you are totally in love with.</p>

<p>ThoughtWorks, being the heavyweight of employment process, has the following approximate steps:</p>

<ul>
<li>HR quick interview</li>
<li>Take home assignment (~2 days part time to complete)</li>
<li>Logic and aptitude test</li>
<li>Tech interview 1</li>
<li>Tech interview 2</li>
<li>Cultutal interview</li>
<li>Management interview</li>
</ul>

<p>Compared to the other places, they are not entirely unreasonable. Although the logic test at TW deserves a special mention as it&#8217;s so so <em>so</em> cool. You basically need to turn you brain into pointer dereferencing CPU for 45 minutes. I&#8217;ve never seen anything like it and a quick search online didn&#8217;t turn up a similar one.</p>

<p>Place 2</p>

<ul>
<li>Online test with the agency</li>
<li>Technical questionaire</li>
<li>Technical interview (this one was 3 hours) </li>
<li>Take home assignment (about the same amount of effort as ThoughWorks)</li>
</ul>

<p>Plase 3</p>

<ul>
<li>Online test</li>
<li>Written test at the place</li>
<li>Tech interview</li>
<li>Cultural interview (with BeardDev 1)</li>
<li>Cultural interview 2. I made it this far at which point they decided I was overqualified. It was annoying and I still don&#8217;t actually agree with them, but it turned out for the better.</li>
</ul>

<p>Place 4 (<strong>the place</strong>)</p>

<ul>
<li>Take home written test</li>
<li>Interview with architect and dev manager (BeardDev 2)</li>
<li>Reference check</li>
<li>Offer </li>
</ul>

<p>So, be prepared. Luckily I liked all the tests, especially take home assignments. Wriating about writing those deserves a separate blog post, as there are nuances that caught me out. Publisising those will make for an interesting read.</p>

<h3>Doing what you love, point 2</h3>

<p>There is a parallel with what happened to me and what my wife is going through at the moment. She loves making parties (invites, themes, decorations, etc). She also loves facebook and not in the time wasting way. She communicates with other mums out there who have babies of similar ages to ours, which has been god sent for her.</p>

<p>By taking the two things shes loves and combining them, she is now on her way to creating a business &#8211; <a href="http://www.printaparty.com.au">printaparty.com.au</a> &#8211; designer party invites and themes you can print at home(the site is designed by her and humbly coded by yours truly). Genius. I have no doubt, she wouldn&#8217;t need to go back to full time work after maternity leave. Turns out facebook is unparalled in promoting an at home (mummy) business.</p>

<p>There something important here, and that is your participation in the community must be genuine. That much is obvious. You don&#8217;t want to be another loud mouth &#8220;guru&#8221; who jumps on whatever bandwagon is in to promote self. People are not dumb and they <strong>will</strong> see through that.</p>

<h3>To wrap it up</h3>

<p>I think it should become clear what the point of this post is. By being geniune and striving for the best, you are well on the way to happiness. This is a very Zen-like approach that seemed to have worked for me, I hope it does for you :)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2011/02/23/how-path-to-happiness-is-surprisingly-doing-what-you-love-and-stackoverflow/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Composite Pattern and Unity IoC container</title>
		<link>http://www.somethingorothersoft.com/2010/12/31/composite-pattern-and-unity-ioc-container/</link>
		<comments>http://www.somethingorothersoft.com/2010/12/31/composite-pattern-and-unity-ioc-container/#comments</comments>
		<pubDate>Fri, 31 Dec 2010 03:16:03 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[unity-configuration-block]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=485</guid>
		<description><![CDATA[Joel Spolsky thinks that IoC containers are an overkill and Dan North agrees that IoC Containers inadvertently tolerate highly inter-dependent designs. IoC containers, in my opinion, are indispensable in creating a loosely coupled application. So much so, that I think that there should be a language that has Dependency Injection built-in. That aside, I have <a href="http://www.somethingorothersoft.com/2010/12/31/composite-pattern-and-unity-ioc-container/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Joel Spolsky <a href="http://stackoverflow.com/questions/871405/why-do-i-need-an-ioc-container-as-opposed-to-straightforward-di-code/871420#871420">thinks</a> that IoC containers are an overkill and Dan North <a href="http://twitter.com/#!/tastapod/status/12054276046061568">agrees</a> that <em>IoC Containers inadvertently tolerate highly inter-dependent designs</em>. IoC containers, in my opinion, are indispensable in creating a loosely coupled application. So much so, that I think that there should be a language that has Dependency Injection built-in.</p>

<p>That aside, I have discovered a feature in <a href="http://unity.codeplex.com/">Unity container</a> that makes implementing a composite pattern kinda fun. Just a brief remainder of what the <a href="http://en.wikipedia.org/wiki/Composite_pattern">composite pattern</a> is. It is a simple pattern where a class implements an interface and delegates invocation on that interface to an internal collection of actual interface implementations. This allows the calling class to treat multiple implementations as one single component.</p>

<p>Generally, this pattern is most appropriate for interface containing methods that have a simple return type or void ( i.e. Command Pattern). I found that things that are called &#8220;SomethingPolicy&#8221; are a good match for this pattern. In this example I will use ASP .NET authorization as an example of how to create a true Open-Closed component using a composite pattern.</p>

<p>For the sake of clarity I will call the class implementing the composite pattern <em>composite class</em> and actual implementations <em>implementation interfaces</em>.</p>

<p>The implementation of this pattern relies on a couple of interesting Unity Container properties.</p>

<p><strong>Property 1:</strong> Items registered with a name are not resolvable through <code>Resolve()</code>. Also remember that a <code>Resolve()</code> call is the same as taking a dependency on that type in the constructor. These registrations are only available when calling <code>ResolveAll()</code>.</p>

<p><strong>Property 2</strong> Items registered without a name are <strong>not</strong> available when calling <code>ResolveAll()</code> and are only available as a result of a call to <code>Resolve()</code>.</p>

<p>This means that you can register the composite class without a name and implementation interfaces as mappings with name. The composite class then becomes the default implementation &#8211; i.e. when someone takes a dependency on that interface in the constructor.</p>

<p><a href="http://stackoverflow.com/questions/780436/asp-mvc-authorize-all-actions-except-a-few">This question</a> describes how to create a base controller that overrides <code>OnAuthorization()</code> method and allows to require authorization by default, without having to decorate all action methods with <code>[Authorize]</code> attribute.</p>

<p>So, here is the base controller:</p>

<div>
<pre class="brush: csharp; title: ; notranslate">
public class BaseController : Controller
{
    private readonly IAuthorizationPolicy _Policy;

    public BaseController(IAuthorizationPolicy policy) {
      _Policy = policy;
    }
   
    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        // Check if this action has NotAuthorizeAttribute
        object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
        if (attributes.Any(a =&gt; a is NotAuthorizeAttribute)) return;

        filterContext.Result = _Policy.Execute(filterContext);
    }
}
</pre>
</div>

<p>Below is the composite class. Note that it takes a constructor parameter of an array of mappings of implementation interface registration to the order in which it should be executed. This allows fine tuning the order in which the policies are executed. Note the near textbook following of SRP, where the logic of executing multiple policies and ordering of invocations is kept out of the controller class. The reason for this collection being an array of key value pairs as opposed to a dictionary is for ease of configuration through XML configuration.</p>

<div>
<pre class="brush: csharp; title: ; notranslate">
    public interface IAuthorizationPolicy {
        ActionResult Execute(AuthorizationContext context);
    }

    public class AuthorizationPolicyComposite : IAuthorizationPolicy{
        
        private KeyValuePair&lt;int, string&gt;[] _NameList;
        private IEnumerable&lt;IRequestPolicy&gt; _Policies;

        /// &lt;summary&gt;
        /// Creates AuthorizationPolicyComposite class.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;dictionary&quot;&gt;priority list of container registration names. E.g. {1,&quot;policy1&quot;} will use the container 
        /// to resolve an instance of &lt;see cref=&quot;IAuthorizationPolicy&quot;/&gt; using &quot;policy1&quot; name and will put that instance in the order specified by the integer.&lt;/param&gt;
        public AuthorizationPolicyComposite(KeyValuePair&lt;string, int&gt;[] dictionary) {
            // TODO: Complete member initialization
            this._NameList = dictionary;

            InitComposite();
        }

        private void InitComposite() {
            _Policies = _NameList
                .OrderBy(item =&gt; item.Value) //sort on order number
                .Select(item =&gt; _Container.Resolve&lt;IAuthorizationPolicy&gt;(item.Key));
        }

        #region IRequestPolicy Members

        public System.Web.Mvc.ActionResult Execute(AuthorizationContext context) {
            foreach(var policy in _Policies) {
                var result = policy.Execute(context);
                if(result != null)
                    return result;
            }
            return null;
        }
    }
</pre>
</div>

<p>The registrations for all of these can be done as follows:</p>

<div>
<pre class="brush: csharp; title: ; notranslate">
private void InitContainer(IUnityContainer container) {
    //composite regisrtation
    container.RegisterType&lt;IAuthorizationPolicy, AuthorizationPolicyComposite&gt;(new Dictionary&lt;string,int&gt; {
        {&quot;normal&quot;, 1},
        {&quot;activation&quot;, 2},
    }.ToArray());
    //normal authorization policy
    container.RegisterType&lt;IAuthorizationPolicy, NormalAuthorizationPolicy&gt;(&quot;normal&quot;);
    //User activation authorization policy - i.e. a user must go through activation process on first login
    container.RegisterType&lt;IAuthorizationPolicy, UserActivationAuthorizationPolicy&gt;(&quot;activation&quot;);
}
</pre>
</div>

<p>That&#8217;s it. The configuration for XML is not included here as it is pretty much the same as the API version. There is a trick to get the <code>KeyValuePair</code>s to work using a converter, but that&#8217;s a topic for another post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/12/31/composite-pattern-and-unity-ioc-container/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Book review: Agile Principles, Patterns, and Practices in C#</title>
		<link>http://www.somethingorothersoft.com/2010/11/30/book-review-agile-principles-patterns-and-practices-in-c/</link>
		<comments>http://www.somethingorothersoft.com/2010/11/30/book-review-agile-principles-patterns-and-practices-in-c/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 12:56:00 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[bookshelf]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[csharp]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=476</guid>
		<description><![CDATA[Review of Bob C. Martin's "Agile Principles, Patterns, and Practices in C#".]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/11/agile-c.jpg"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/11/agile-c.jpg" alt="" title="agile c#" width="372" height="500" class="alignnone size-full wp-image-477" /></a></p>

<p>Bob C. Martin&#8217;s *Agile Principles, Patterns, and Practices in C#&#8221; has to be the most readable and enjoyable computer text ever written. Having created production object orientated code for years, seeing ways to do OO properly is eye opening. Reflecting back, I realise that a lot of that &#8220;OO&#8221; code is actually procedural code written using OO tools.</p>

<p>A lot of the patterns described in the book are really there to enforce one of the guiding principles &#8211; Single Responsibility Principle (SRP). By looking at designing your system through the SRP lens, a lot of things become clearer.</p>

<p>In OO classes are first class citizens, and as a C++ developer, having one method classes seemed like a waste. Sounds silly, but I thought that a class should have lots of methods in order for it to be useful. Having now opened the door to designing loosely coupled system with lots of coherent classes, there is no going back.</p>

<p>I think this should be one of the main tenets tought in OO classes &#8211; THERE IS NOTHING WRONG WITH SMALL CLASSES. &#8220;Saving&#8221; classes by bundling lots of functionality into them has to be eradicated early in OO education.</p>

<p>Back to the book. As I mentioned before, having C++ background made this book even more fun to read as I could tell that the code was originally written in C++. Most of the code is .NET 1.1 and that might be the only minor criticism &#8211;  sample code does not have most of the new features of even .NET 2.0 (e.g. generics). I would also like to see what would happen if this book was rewritten to take into account functional aspects of .NET 3.5 &#8211; lambdas, LINQ libraries, Expressions.</p>

<p>Another valuable insight that I found particularly useful is working through the design to figure out if a pattern application is necessary. A lot of the time design patterns can become &#8220;golden hammers&#8221; of software teams, it&#8217;s good to know when to stop and evaluate if a pattern is needed.</p>

<p>Overall, this is a must read for any developer. C++, Java or C# people will all get something out of it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/11/30/book-review-agile-principles-patterns-and-practices-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CRTP in C#</title>
		<link>http://www.somethingorothersoft.com/2010/09/27/crtp-in-c/</link>
		<comments>http://www.somethingorothersoft.com/2010/09/27/crtp-in-c/#comments</comments>
		<pubDate>Mon, 27 Sep 2010 07:02:56 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[csharp]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=449</guid>
		<description><![CDATA[Curiously Recursive Template Pattern made possible in C#.]]></description>
			<content:encoded><![CDATA[<p>C++ developers are well familiar with the <a href="http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern">CRTP</a> &#8211; Curiously Recurring Template Pattern, where a class can derive from another class, specifying itself as a template parameter.</p>

<p>Every now and then I wish this pattern can be used in C#. If you attempt to implement it C++ style, you would get a compile error:</p>

<div>
<pre class="brush: csharp; title: ; notranslate">
    public abstract class Base&lt;T&gt; {
        public T FluentMethod() {
            return (T)(this); //error CS0030: Cannot convert type 'InheritanceTest.Base&lt;T&gt;' to 'T'
        }
    }

    public class Derived : Base&lt;Derived&gt; {
    }
</pre>
</div>

<p>This is probably a point at which you give up and find another way of doing things. It is, however, possible to implement a fully functioning curiously recurring class system in C# by simply adding a constraint to the base class like so:</p>

<div>
<pre class="brush: csharp; title: ; notranslate">
    public abstract class Base&lt;T&gt; where T : Base&lt;T&gt;{
        public T FluentMethod() {
            return (T)(this); 
        }
    }

    public class Derived : Base&lt;Derived&gt; {
    }
</pre>
</div>

<p>If you attempt to read the constraint your brain will probably spin in infinite circles trying to figure out how it is even possible for a type parameter to be the same as the class itself. The fact that it works, however, is not more magic than the C++ version, where the recursive nature of the class declaration simply compiles. What the constraint really says is that <em>T is a class that derives from Base<T></em>, which is what <code>Derived</code> is.</p>

<p>Another observation. You cannot use <code>Base&lt;T&gt;</code> by itself. It <em>must</em> be inherited from. The <code>abstract</code> keyword is not compulsory, it will compile without it. You just won&#8217;t be able to declare an instance of <code>Base&lt;T&gt;</code> by itself.</p>

<p>This post joins a long list of posts that are inspired by <a href="http://stackoverflow.com/questions/3783321/why-does-this-generic-constraint-compile-when-it-seems-to-have-a-circular-referen/3783459#3783459">one of my StackOverflow answers</a>. The code that uses this pattern can be found in <a href="http://mvccontrib.codeplex.com/SourceControl/changeset/view/b7039b7291cf#src%2fMvcContrib.FluentHtml%2fElements%2fButtonBase.cs">MVCContrib project</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/09/27/crtp-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Type-safe Dynamic Mixins</title>
		<link>http://www.somethingorothersoft.com/2010/08/12/type-safe-dynamic-mixins/</link>
		<comments>http://www.somethingorothersoft.com/2010/08/12/type-safe-dynamic-mixins/#comments</comments>
		<pubDate>Thu, 12 Aug 2010 13:34:29 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=433</guid>
		<description><![CDATA[This is another one of those posts that arose from an epic StackOverflow answer. The problem to be solved was creating a factory that would at runtime merge two implementations of different interfaces into one object. I have implemented this using Castle Dynamic Proxy (which is totally awesome, that&#8217;s why all mocking/testing libraries use it). <a href="http://www.somethingorothersoft.com/2010/08/12/type-safe-dynamic-mixins/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>This is another one of those posts that arose from an <a href="http://stackoverflow.com/questions/3411294/is-it-possible-in-c-to-make-a-factory-that-merges-interfaces/3414970#3414970">epic StackOverflow answer</a>.</p>

<p>The problem to be solved was creating a factory that would at runtime merge two implementations of different interfaces into one object. I have implemented this using Castle Dynamic Proxy (which is totally awesome, that&#8217;s why all mocking/testing libraries use it).</p>

<p>In this post I want to concentrate more on the performance aspects of the solution and provide source code for your own perusal. There are two implementations of <code>CreateMixin</code> &#8211; generic and non-generic versions. They are completely different in how they mix interfaces.</p>

<h3><code>CreateMixin</code></h3>

<p>The non-generic version simply leverages Castle Dynamic Proxy mixins to bundle objects into one instance. The downside is that all of those interfaces are implemented explicitly and the returned instance must be cast to each individual interface to be used. Here is the implementation and the unit test:</p>

<div>
<pre class="brush: csharp; title: ; notranslate">
public static object CreateMixin(params object[] instances) {

    ProxyGenerator generator = new ProxyGenerator();
    ProxyGenerationOptions options = new ProxyGenerationOptions();

    instances.ToList().ForEach(obj =&gt; options.AddMixinInstance(obj));

    return generator.CreateClassProxy&lt;object&gt;(options);
}
[TestMethod]
public void CreatedMixinShouldntThrow() {
    ICat obj1 = new Cat();
    IDog obj2 = new Dog();

    var actual = Factory.CreateMixin(obj1, obj2);
    ((IDog)actual).Bark();
    var weight = ((IDog)actual).Weight;
    ((ICat)actual).Meow();
    var age = ((ICat)actual).Age;
}
</pre>
</div>

<h3><code>CreateMixin&lt;T&gt;</code></h3>

<p>While I was playing around with it I thought I&#8217;d create another factory method that could return a strongly typed version of the super object. This turned out to be tricky as this was a bit like having cake and eating it too.</p>

<p>The initial implementation was fairly slow in comparison to the native class implementation (i.e. fully implemented at compile time) &#8211; about a thousand times slower. The Castle DP mixin performance on the other hand was pretty good. The breakdown was something like this:</p>

<ul>
<li>Native ~10ms</li>
<li>Mixin ~300ms</li>
<li>Generic mixin ~10000ms</li>
</ul>

<p>The culprit, as expected, was this bit of code. It uses reflection and is extremely slow compared to native or even Castle mixins.</p>

<div>
<pre class="brush: csharp; title: ; notranslate">
    public void Intercept(IInvocation invocation) {
        invocation.ReturnValue = invocation.Method.Invoke(m_Instance, invocation.Arguments);
    }
</pre>
</div>

<p>After digging around Dynamic proxy code I have found <code>IChangeProxyTarget</code> interface that allows to change the target of invocation in the interceptor. Since we want to simply redirect a call from the combined interface to the implementation, all we need to do is point the invocation towards the actual instance.</p>

<div>
<pre class="brush: csharp; title: ; notranslate">

public void Intercept(IInvocation invocation) {
    IChangeProxyTarget changeTarget = (IChangeProxyTarget)invocation;
    changeTarget.ChangeInvocationTarget(m_Target);
    invocation.Proceed();
}
</pre>
</div>

<p>The only icky bit about this is the fact that we need to call <code>CreateInterfaceProxyWithTargetInterface</code> in order to be able to switch target of invocation in the interceptor method. What this implies, however is that we need to provide an instance of the combined interface (which never gets used anyway), so we actually create another proxy and pass that to the proxy creation method. A bit recursive, but it gets the job done.</p>

<p>And here is the factory method with test:</p>

<div>
<pre class="brush: csharp; title: ; notranslate">
public static TMixin CreateMixin&lt;TMixin&gt;(params object[] instances)
where TMixin : class {
    if(instances == null || instances.Length == 0 || instances.Any(o =&gt; o == null))
        throw new ArgumentException(&quot;All mixins should be non-null&quot;, &quot;instances&quot;);

    ProxyGenerator generator = new ProxyGenerator();
    ProxyGenerationOptions options = new ProxyGenerationOptions();
    options.Selector = new MixinSelector();
    var dummy = generator.CreateInterfaceProxyWithoutTarget&lt;TMixin&gt;();

    return generator.CreateInterfaceProxyWithTargetInterface&lt;TMixin&gt;(dummy, options, instances.Select(o =&gt; new MixinInterceptor(o)).ToArray());
}
[TestMethod]
public void CreatedGeneric3MixinShouldntThrow() {
    ICat obj1 = new Cat();
    IDog obj2 = new Dog();
    IMouse obj3 = new Mouse();
    var actual = Factory.CreateMixin&lt;ICatDogMouse&gt;(obj1, obj2, obj3);

    actual.Bark();
    var weight = actual.Weight;
    actual.Meow();
    var age = actual.Age;
    actual.Squeek();
}
</pre>
</div>

<p>The result is that performance is improved by a lot:</p>

<ul>
<li>Native ~10ms</li>
<li>Mixin ~300ms</li>
<li>Generic mixin ~500ms</li>
</ul>

<p>Oh and by the way, this is for 8M invocations. So it&#8217;s not that big of a hit in realistic terms. I wouldn&#8217;t run this in a very tight loop &#8211; e.g. image processing or anything real time but it&#8217;s quite suitable for calling some service every now and again.</p>

<p><a href='http://www.somethingorothersoft.com/wp-content/uploads/2010/08/MixinFactory.zip'>MixinFactory Source</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/08/12/type-safe-dynamic-mixins/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Handling 404, unhandled and unsafe URL errors in ASP.NET MVC application</title>
		<link>http://www.somethingorothersoft.com/2010/06/18/handling-404-unhandled-and-unsafe-url-errors-in-asp-net-mvc-application/</link>
		<comments>http://www.somethingorothersoft.com/2010/06/18/handling-404-unhandled-and-unsafe-url-errors-in-asp-net-mvc-application/#comments</comments>
		<pubDate>Fri, 18 Jun 2010 00:15:36 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[asp.net-mvc]]></category>
		<category><![CDATA[csharp]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=411</guid>
		<description><![CDATA[Spent a bit of time recently to try and get my MVC application handle 404 errors exactly as I want. The solution that I ended up choosing is based on this excellent SO answer. The advantage of rendering the Error view by calling ErrorController.Execute, as opposed to making an entry in web.config, is that you <a href="http://www.somethingorothersoft.com/2010/06/18/handling-404-unhandled-and-unsafe-url-errors-in-asp-net-mvc-application/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Spent a bit of time recently to try and get my MVC application handle 404 errors exactly as I want. The solution that I ended up choosing is based on this excellent <a href="http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/2577095#2577095">SO answer</a>.</p>

<p>The advantage of rendering the Error view by calling <code>ErrorController.Execute</code>, as opposed to making an entry in web.config, is that you get to preserve the URL without a browser redirect.</p>

<p>If you think about which scenarios warrant a 404 response a more involved strategy is justifiable:</p>

<ol>
<li>Non-supported controller name &#8211; captured by <code>{controller}/{action}/{parameter}</code> rule.</li>
<li>Supported controller but bad action &#8211; captured by <code>Controller.HandleUnknownAction</code>.</li>
<li>Non-supported URL format &#8211; captured by the catch-all rule.</li>
</ol>

<p>Using <code>ErrorController.Execute</code> allows to preserve the URL for all of those scenarios. Now, to trap all unhandled exceptions in order to not show a Yellow Screen of Death, you would need to do some error handling in <code>Application.Error</code> event handler. Something similar is described in <a href="http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/620559#620559">this answer</a>.</p>

<p>There is a catch, however. If the anti-XSS features kick in and disallow a URL containing, say, angle brackets, executing error controller from global exception handler will throw an exception resulting in a YSOD.</p>

<p>The best solution i found was to catch the exception when doing <code>Execute</code> and do a browser redirect then. This prevents the runtime from creating a YSOD due to an unhandled exception in the exception event.</p>

<div>
<pre class="brush: csharp; title: ; notranslate">
IController errorController = ControllerBuilder.Current.GetControllerFactory().CreateController(null, &quot;error&quot;);
try {
    errorController.Execute(new RequestContext(
            contextBase, errorRoute));
} catch(Exception) {
    //If we are here it means that the URL is unsafe and the only way to handle it gracefully is to redirect.
    Response.Redirect(&quot;~/Error/BadRequest&quot;); //Controller/View pair that returns 400 - Bad Request
}

</pre>
</div>

<p>It&#8217;s probably not the best idea to handle 400 error as 404, hence we redirect to a &#8220;BadRequest&#8221; action in the <code>ErrorController</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/06/18/handling-404-unhandled-and-unsafe-url-errors-in-asp-net-mvc-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Keeping your sanity whilst developing for Windows Phone 7</title>
		<link>http://www.somethingorothersoft.com/2010/04/28/keeping-your-sanity-whilst-developing-for-windows-phone-7/</link>
		<comments>http://www.somethingorothersoft.com/2010/04/28/keeping-your-sanity-whilst-developing-for-windows-phone-7/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 23:04:18 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[windows-phone-7]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=368</guid>
		<description><![CDATA[Dealing with those obtuse run-time errors whilst developing for WP7.

<img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/frustration-300x299.jpg"/>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/frustration-300x299.jpg"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/frustration-300x299.jpg" alt="" title="frustration-300x299" width="300" height="299" class="alignnone size-full wp-image-380" /></a></p>

<p>Please note that this post is written in April 2010, when the WP7 SDK is only one month old. Most of the issues described here will likely not be a problem in later releases. The defining characteristic of such pre-release SDK is that when you are doing the right thing, everything is OK. When you screw up, it just goes KABOOM! without much explanation.</p>

<p>I spent a few hours of trying to work out why I am getting these run-time errors and so I&#8217;ve put together a list of the most painful ones, enjoy.</p>

<h2>Using <code>{x:Static ...}</code> Syntax</h2>

<p><strong>Problem:</strong> <code>{x:Static ...}</code> is not supported in Silverlight.</p>

<p>If you to do something like this:</p>

<div><pre class="brush: xml; title: ; notranslate">
&lt;DiscreteObjectKeyFrame  KeyTime=&quot;00:00:00&quot; Value=&quot;{x:Static Visibility.Collapsed}&quot;&gt;
</pre></div>

<p>You will get an obtuse error at runtime:</p>

<p><pre>
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in System.Windows.dll
Additional information: 2024 An error has occurred. [Line: 114 Position: 61]
</pre></p>

<p>Get used to seeing that error. It&#8217;ll happen every time you screw up the XAML. Sometimes it&#8217;s more helpful than other times and you get the line number of the offending XAML. The line number, along with the exception text will be available in the Output window:</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/crash1.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/crash1-1024x611.png" alt="" title="crash1" width="450" height="268" class="alignnone size-large wp-image-369" /></a></p>

<p>If you are like me and rarely look at the error window, perhaps you should start now. This particular error doesn&#8217;t raise a warning during compilation, but does come up as an error when the file is open in the editor:</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/xaml_error.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/xaml_error.png" alt="" title="xaml_error" width="641" height="262" class="alignnone size-full wp-image-370" /></a></p>

<p><strong>Solution:</strong> Don&#8217;t use <code>x:Static</code> but instead an instance of a type in XAML like so:</p>

<div><pre class="brush: xml; title: ; notranslate">
    &lt;DiscreteObjectKeyFrame  KeyTime=&quot;00:00:00&quot;&gt;
        &lt;DiscreteObjectKeyFrame.Value&gt;
            &lt;Visibility&gt;Collapsed&lt;/Visibility&gt;
        &lt;/DiscreteObjectKeyFrame.Value&gt;
    &lt;/DiscreteObjectKeyFrame&gt;
</pre></div>

<h2>Misspelling Animation Element or Property Name</h2>

<p><strong>Problem:</strong> Misspelling Animation Element or Property Name</p>

<p>In the below code <code>Storyboard.TargetName</code> is invalid. The project compiles and there are no errors in the error window.</p>

<div><pre class="brush: xml; title: ; notranslate">
    &lt;ObjectAnimationUsingKeyFrames Storyboard.TargetName=&quot;SearchBoxMisspelled&quot; Storyboard.TargetProperty=&quot;Visibility&quot;&gt;
        &lt;!--animation key frames--&gt;
    &lt;/ObjectAnimationUsingKeyFrames&gt;
</pre></div>

<p>At run-time, you get this error message:</p>

<p><pre>
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.dll
Additional information: 2213 An error has occurred.
</pre></p>

<p>The call stack only tells you that this is something to do with the animation:</p>

<p><pre>
System.Windows.dll!MS.Internal.XcpImports.MethodEx(System.IntPtr ptr = 146517008, string name = "Begin", MS.Internal.CValue[] cvData = null) + 0x9d bytes
System.Windows.dll!MS.Internal.XcpImports.MethodEx(System.Windows.DependencyObject obj = {System.Windows.Media.Animation.Storyboard}, string name = "Begin") + 0x6 bytes<br />
System.Windows.dll!MS.Internal.XcpImports.Storyboard_Begin(System.Windows.Media.Animation.Storyboard storyboard = {System.Windows.Media.Animation.Storyboard})
System.Windows.dll!System.Windows.Media.Animation.Storyboard.Begin() + 0x6 bytes
</pre></p>

<p><strong>Solution:</strong> To resolve this, check your animation element and property names. Unfortunately I haven&#8217;t found a way to get at the offending animation frame from the call stack. Would be happy to find out if there is a way.</p>

<h2>References&#8217; Dependencies</h2>

<p><strong>Problem:</strong> &#8220;Object reference is not set to an instance of an object&#8221; error when debugging and crashes when running without debugger.</p>

<p>After adding a reference library you might start getting this error when you debug the project:</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/error_debugging.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/error_debugging.png" alt="" title="error_debugging" width="391" height="171" class="alignnone size-full wp-image-371" /></a></p>

<p>This is caused, as far as I can tell, by your references&#8217; dependencies not being copied to the device. After hours of playing around with this it&#8217;s apparent to me that this is an intermittent issue with Visual Studio. It is supposed to work out what all the references&#8217; dependencies are, copy them to the output folder and add them to the manifest file (<code>$(OutputDir)\AppManifest.xaml</code>).</p>

<p>Sometimes that doesn&#8217;t happen and the app gets deployed without those dependencies. It will still work, up until the point where a class is referenced from a dependant assembly and that assembly cannot be loaded. I expect this problem to go away in later releases of WP7 SDK.</p>

<p>The error will look something like this:</p>

<p><a href="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/runtime_error.png"><img src="http://www.somethingorothersoft.com/wp-content/uploads/2010/04/runtime_error.png" alt="" title="runtime_error" width="396" height="772" class="alignnone size-full wp-image-372" /></a></p>

<p><pre>
2024 An error has occurred[Line: <line> Position: <position>]
at
System.Windows.Application.LoadComponent
...Rest of the callstack.
</pre></p>

<p><strong>Solution:</strong> Add all the assembiles that your references depend upon as references to the project.
<strong>Edit:</strong> This error kept happening to me until my coworker pointed out the solution, which led to the &#8220;Doh moment of the week.&#8221;
<strong>Solution2:</strong> When debugging the project <strong>select the project in the solution pane and press F5</strong>. Yeah, that simple.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/04/28/keeping-your-sanity-whilst-developing-for-windows-phone-7/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>F# &#8211; Combinators And Tail Recursion</title>
		<link>http://www.somethingorothersoft.com/2010/03/01/f-combinators-and-tail-recursion/</link>
		<comments>http://www.somethingorothersoft.com/2010/03/01/f-combinators-and-tail-recursion/#comments</comments>
		<pubDate>Sun, 28 Feb 2010 21:37:08 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[f#]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=312</guid>
		<description><![CDATA[Perhaps combinators and tail recursion are not the best beginner topics in F# but they are the ones I got stuck into pretty much straight away. I blame Google. After reading a few google hits on functional programming I of course found out about combinators and I just had to understand them. I finally got <a href="http://www.somethingorothersoft.com/2010/03/01/f-combinators-and-tail-recursion/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>Perhaps combinators and tail recursion are not the best beginner topics in F# but they are the ones I got stuck into pretty much straight away. I blame Google. After reading a few google hits on functional programming I of course found out about combinators and I just had to understand them.</p>

<p>I finally got it but it took a while. The issue, particularly in F#, is that combinators don&#8217;t make all that much sense as a substitute for non-recursive functions. After all, the only way to run the combinator recursively is with a recursive function (as in <code>let rec</code>). A different solution might be to use recursive types, but that&#8217;s is pretty pointless. There was a great <a href="http://stackoverflow.com/questions/1998407/how-do-i-define-y-combinator-without-let-rec">StackOverflow question</a> about that by the way.</p>

<h3>What is a combinator</h3>

<p>I am getting ahead of myself though. Combinators are a mathematical concept pioneered by Haskell Curry. The essence of combinators is that they allow sophisticated computation by combining simple functions. Hence the term combinator. Combinators allow a recursive algorithm to be written using a function that does not call itself but instead invokes another function that is passed in as one of the arguments.</p>

<p>One distinct characteristic of a combinator function is that all of its variables are bound. That means that the function only depends on its parameters, not any other data structures or function defined elsewhere. Just about the best description of what is a combinator and what isn&#8217;t can be found <a href="http://mvanier.livejournal.com/2897.html">here</a></p>

<div>
<pre class="brush: fsharp; title: ; notranslate">
let freevar=3 //a variable

let IAmACombinator x = x*2;; //variable x is bound as a formal parameter
let IAmNotACombinator x = x*y;; x is bound but y is free. This is not a combinator
</pre>
</div>

<h3>Example</h3>

<p>Lets do some examples. An algorithm that I will implement is the sum of arithmetic  progression. It&#8217;s an algorithm that can really be solved in O(1) time (by using the formula (m+n)*(m-n+1)/2, but it makes for good tail recursion test (i.e. you can blow the stack quite easily, unlike the factorial, which runs out of the integer range at about 15).</p>

<p>This is the normal recursive arithmetic progression function:</p>

<div>
<pre class="brush: fsharp; title: ; notranslate">
let rec progsum x =  
    if x &lt;= 1 then 1 
    else x+progsum (x-1)
</pre>
</div>

<h3>Combinator Version</h3>

<p>Thanks to F# type inference, the  combinator function is pretty the same for any application and only depends on the number of parameters to the worker function.</p>

<p>This is the combinator version of the above function:</p>

<div>
<pre class="brush: fsharp; title: ; notranslate">
//Normal arithmentic progression sum combinator
let rec comb f = f (fun x -&gt; comb f x)
let progworker f x = 
    if x &lt;= 1 then 1 
    else x+f(x-1)
//Use partial application to wrap up the combinator call    
let progCombinator x = comb progworker x ;;
</pre>
</div>

<p>This might need a bit of explaining. <code>comb</code> is a higher order function that takes another function as a parameter and returns a function taking one argument. This returned function is what we actually want &#8211; a function taking one parameter and returning something of the same type as the parameter.</p>

<p>In the above snippet <code>progCombinator</code> is a convenient way to partially apply our combinator to the arithmetic progression worker function. We could have just as easily done for a factorial:</p>

<div>
<pre class="brush: fsharp; title: ; notranslate">
let factworker f x = 
    if x &lt;= 1 then 1
    else f(x-1) * x;;
//Use partial application to wrap up the combinator call    
let factCombinator x = comb factworker x ;;
</pre>
</div>

<h3>Tail recursion</h3>

<p><em>Tail Call Optimization</em> is an F# compiler feature (and in some cases <a href="http://blogs.msdn.com/jomo_fisher/archive/2007/09/19/adventures-in-f-tail-recursion-in-three-languages.aspx">JIT Compiler feature</a>) where it will transform a recursive function into a while loop if the recursive call is the last statement in the function. Let&#8217;s go back to the original arithmetic progression function and see if that is the case:</p>

<div>
<pre class="brush: fsharp; title: ; notranslate">
let rec progsum x =  
    if x &lt;= 1 then 1 
    else x+progsum(x-1)
</pre>
</div>

<p>And it isn&#8217;t. Even though it looks like the function call is the last statement of the function, <code>progsum(x+1)</code>  will be evaluated before <code>x+progsum(x+1)</code> can be computed. Let&#8217;s rewrite it to take advantage of tail recursion:</p>

<div>
<pre class="brush: fsharp; title: ; notranslate">
let progTR x =  
    let rec inner x sum = 
        if x &lt;= 1 then sum 
        else inner (x-1) (sum + x)
    inner x 1;;
</pre>
</div>

<p>So, what happened here? Well, for once we declared a wrapper function and the worker function inside it. This is not strictly necessary, but allows to hide some of the implementation semantics. So, if we can visualize how the original function worked, this is a crude diagram that shows the execution path for <code>x = 4</code>:</p>

<p><pre>
progsum 4
->calls progsum 3
  ->calls progsum 2
    ->calls progsum 1
       ->returns 1
    <-returns (progsum 1) + 2
  <-returns (progsum 2) + 3
<-returns (progsum 3) + 4
</pre></p>

<p>As you can see the result is computed "on the way out" - i.e. as the function returns. In the tail recursive version we compute the result "on the way in", which allows the recursive function invocation to be the last statement in the function. Here is the diagram:</p>

<p><pre>
inner 4 1
->calls inner 3 (1 + 4)
  ->calls inner 2 (5 + 3)
    ->calls inner 1 (8 + 2)
      -> returns 10
    <-returns 10
  <-returns 10
<-returns 10
</pre></p>

<p>An interesting side effect of this tail recursive function is the fact that the order in which sum happens is not quite the same as in the original function.</p>

<p>Original:</p>

<p><pre>
4 + (3 + (2 +(1)))
</pre></p>

<p>Tail Recursive:</p>

<p><pre>
((4 + 1) + 3) + 2
</pre></p>

<h3>Tail Recursive Combinator</h3>

<p>So, now that we've gone over combinator functions and tail recursive functions you may ask: "What about tail recursive combinators? Do those exist?". And the answer would be "Yes, indeed, such beasts do exist". Here is the same algorithm implemented as a tail recursive combinator:</p>

<div>
<pre class="brush: fsharp; title: ; notranslate">
let rec combTR f = f (fun x acc -&gt; combTR f x acc)
let progTR f x acc = 
    match x with
    | 1 -&gt; acc
    | x -&gt; f(x-1) (acc + x);;
    
let progCombTR x = combTR progTR x 1;;
</pre>
</div>

<p>Looking at the code, there is nothing groundbreaking there. Just as we converted the original function into a tail recursive function by adding a second parameter, we did the same for the both the combinator function and the inner function.</p>

<p>For more details on tail recursion and different ways to optimise it have a look <a href="http://thevalerios.net/matt/2009/01/recursion-in-f-and-the-tail-recursion-police/">here</a> and <a href="http://blogs.msdn.com/jomo_fisher/archive/2007/09/19/adventures-in-f-tail-recursion-in-three-languages.aspx">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/03/01/f-combinators-and-tail-recursion/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Double dispatch without RTTI</title>
		<link>http://www.somethingorothersoft.com/2010/02/01/double-dispatch-without-rtti/</link>
		<comments>http://www.somethingorothersoft.com/2010/02/01/double-dispatch-without-rtti/#comments</comments>
		<pubDate>Sun, 31 Jan 2010 22:15:16 +0000</pubDate>
		<dc:creator>igor</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[c++]]></category>

		<guid isPermaLink="false">http://www.somethingorothersoft.com/?p=230</guid>
		<description><![CDATA[I liked my StackOverflow answer so much that I decided to make it into a blog post. The question was how to implement a double dispatch mechanism for subclasses of one base class without casting. After dismissing the question as stupid, I spent a bit of time trying to come up with a solution that <a href="http://www.somethingorothersoft.com/2010/02/01/double-dispatch-without-rtti/" rel="bookmark" title="Read on...">[...]</a>]]></description>
			<content:encoded><![CDATA[<p>I liked my <a href="http://stackoverflow.com/questions/2159496/c-problem-with-function-overloading/2159524#2159524">StackOverflow answer</a> so much that I decided to make it into a blog post. The question was how to implement a double dispatch mechanism for subclasses of one base class without casting. After dismissing the question as stupid, I spent a bit of time trying to come up with a solution that didn&#8217;t rely on <code>dynamic_cast</code>. The solution is pretty pointless as it&#8217;s pretty confusing and might be slower than RTTI solution due to an extra function call. It was largely inspired by wikipedia article on double dispatch found <a href="http://en.wikipedia.org/wiki/Double_dispatch">here</a>.</p>

<p>So the trick to get this working as pointed out in the article was to call the function on the pointer or reference of the parameter to the original function, thus cauising a second dispatch.</p>

<div class="foo">
<pre class="brush: cpp; title: ; notranslate">
class A {
  virtual void PublicFunction(B&amp; b) {
    b.PerformFunction(*this);
  }
}
</pre>
</div>

<p>The problem with doing this sort of thing with subclasses of the same base is that we need to allow the possibility of the base class being called with one of its subclasses as a parameter. Luckily we can use forward declarations to define the functions and implement them later on.</p>

<div class="foo">
<pre class="brush: cpp; title: ; notranslate">
class b;
class c;
class a {
protected:
    virtual void doFoobar(a&amp; a2); //do stuff here 
    virtual void doFoobar(b&amp; b2); //delegate to b
    virtual void doFoobar(c&amp; c2); //delegate to c
public:
    virtual void foobar(a&amp; a2) {
        a2.doFoobar(*this);
    }
    friend class b;
    friend class c;
};
class b : public a {
protected:
    virtual void doFoobar(a&amp; a2); //do stuff here 
    virtual void doFoobar(b&amp; b2); //do stuff here
    virtual void doFoobar(c&amp; c2); //delegate to c
public:
    virtual void foobar(a&amp; a2) {
        a2.doFoobar(*this);
    }
    friend class a;
};
class c : public b {
protected:
    virtual void doFoobar(a&amp; a2); //do stuff here 
    virtual void doFoobar(b&amp; b2); //do stuff here
    virtual void doFoobar(c&amp; c2); //delegate to c
public:
    virtual void foobar(a&amp; a2) {
        a2.doFoobar(*this);
    }
    friend class a;
    friend class b;
};
//class a
void a::doFoobar(a&amp; a2)  {
    printf(&quot;Doing a&lt;-&gt;a\n&quot;);
}
void a::doFoobar(b&amp; b2)  {
    b2.doFoobar(*this);
}
void a::doFoobar(c&amp; c2)  {
    c2.doFoobar(*this);
}
//class b
void b::doFoobar(a&amp; a2)  {
    printf(&quot;Doing b&lt;-&gt;a\n&quot;);
}
void b::doFoobar(b&amp; b2)  {
    printf(&quot;Doing b&lt;-&gt;b\n&quot;);
}
void b::doFoobar(c&amp; c2)  {
    c2.doFoobar(*this);
}
//class c
void c::doFoobar(a&amp; a2)  {
    printf(&quot;Doing c&lt;-&gt;a\n&quot;);
}
void c::doFoobar(b&amp; b2)  {
    printf(&quot;Doing c&lt;-&gt;b\n&quot;);
}
void c::doFoobar(c&amp; c2)  {
    printf(&quot;Doing c&lt;-&gt;c\n&quot;);
}
</pre>
</div>

<p>The code is far from an ideal double dispatch solution as it relies on the forward declaration trick to resolve the circular dependency between the subclasses. This means that all the classes that need to have this functionality must be known at compile-time (of the base class). This means the base class cannot be made into a library component.</p>

<p>To explain all the friend declarations. Considering the fact that all the classes <code>a</code>, <code>b</code> and <code>c</code> are tightly coupled as is, I added friend declarations so that the actual worker function is private and cannot be called from the outside.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.somethingorothersoft.com/2010/02/01/double-dispatch-without-rtti/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

