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

<channel>
	<title>Whathecode</title>
	<atom:link href="http://whathecode.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://whathecode.wordpress.com</link>
	<description>Discussions on software design.</description>
	<lastBuildDate>Mon, 20 Feb 2012 00:15:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='whathecode.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Whathecode</title>
		<link>http://whathecode.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://whathecode.wordpress.com/osd.xml" title="Whathecode" />
	<atom:link rel='hub' href='http://whathecode.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Downcasting, what&#8217;s up with that?</title>
		<link>http://whathecode.wordpress.com/2011/12/22/downcasting-whats-up-with-that/</link>
		<comments>http://whathecode.wordpress.com/2011/12/22/downcasting-whats-up-with-that/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 13:46:13 +0000</pubDate>
		<dc:creator>Steven Jeuris</dc:creator>
				<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://whathecode.wordpress.com/?p=998</guid>
		<description><![CDATA[Just a short post today, or a question rather, on what must be the easiest subject I&#8217;ve written about yet. Though, I&#8217;ve caught myself making errors against it often. Nowadays I&#8217;m extra cautious when writing about inheritance. What do you think about first when you hear &#8220;up&#8221;? What do you think about first when you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=998&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Just a short post today, or a question rather, on what must be the easiest subject I&#8217;ve written about yet. Though, I&#8217;ve caught myself making errors against it often. Nowadays I&#8217;m extra cautious when writing about inheritance.</p>
<p>What do you think about first when you hear <strong><em>&#8220;up&#8221;</em></strong>?</p>
<p><img class="alignnone" src="http://simplyzesty.com/wp-content/uploads//2011/11/graph_up.jpg" alt="" width="240" height="188" /><img class="alignnone" src="http://www.viagraguide.org/images/viagra.jpg" alt="" width="221" height="166" /><img class="alignnone" src="http://media.smithsonianmag.com/images/consequences-of-evolution-631.jpg" alt="" width="335" height="158" /><img class="alignnone" src="http://images.mylot.com/userImages/images/postphotos/2340956.jpg" alt="" width="194" height="194" /></p>
<p>What do you think about first when you hear <em><strong>&#8220;down&#8221;</strong></em>?</p>
<p><img class="alignnone" src="http://www.clipartoday.com/_thumbs/014/FacePlant_l_tns.png" alt="" width="128" height="117" /><img class="alignnone" src="http://paidcontent.org/images/editorial/_original/arrow-down-o.jpg" alt="" width="166" height="166" /><img class="alignnone" src="http://t3.gstatic.com/images?q=tbn:ANd9GcRXrQU42gxWGK5x4nq92BNk72oRGAIhlsAFM_oIyCHK5iMTrWWroFnnGcvOIQ" alt="" width="233" height="175" /></p>
<p>&nbsp;</p>
<p>Now, how do we programmers interpret <strong>upcasting </strong>and<strong> downcasting</strong>?</p>
<p><img class="alignnone" src="http://img36.imageshack.us/img36/1106/updown.png" alt="" width="418" height="311" /></p>
<p>You <em>upcast</em> to an object which <strong>can do less</strong>, and you <em>downcast</em> to an object which <strong>can do more</strong>.</p>
<p><a href="http://www.youtube.com/watch?v=DUKRIV3cOoc">What&#8217;s up with that?</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whathecode.wordpress.com/998/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whathecode.wordpress.com/998/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whathecode.wordpress.com/998/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whathecode.wordpress.com/998/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whathecode.wordpress.com/998/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whathecode.wordpress.com/998/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whathecode.wordpress.com/998/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whathecode.wordpress.com/998/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whathecode.wordpress.com/998/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whathecode.wordpress.com/998/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whathecode.wordpress.com/998/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whathecode.wordpress.com/998/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whathecode.wordpress.com/998/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whathecode.wordpress.com/998/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=998&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whathecode.wordpress.com/2011/12/22/downcasting-whats-up-with-that/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2648f806f3af808a2ed537c8e745558e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">whathecode</media:title>
		</media:content>

		<media:content url="http://simplyzesty.com/wp-content/uploads//2011/11/graph_up.jpg" medium="image" />

		<media:content url="http://www.viagraguide.org/images/viagra.jpg" medium="image" />

		<media:content url="http://media.smithsonianmag.com/images/consequences-of-evolution-631.jpg" medium="image" />

		<media:content url="http://images.mylot.com/userImages/images/postphotos/2340956.jpg" medium="image" />

		<media:content url="http://www.clipartoday.com/_thumbs/014/FacePlant_l_tns.png" medium="image" />

		<media:content url="http://paidcontent.org/images/editorial/_original/arrow-down-o.jpg" medium="image" />

		<media:content url="http://t3.gstatic.com/images?q=tbn:ANd9GcRXrQU42gxWGK5x4nq92BNk72oRGAIhlsAFM_oIyCHK5iMTrWWroFnnGcvOIQ" medium="image" />

		<media:content url="http://img36.imageshack.us/img36/1106/updown.png" medium="image" />
	</item>
		<item>
		<title>Massive-scale Online Software Development</title>
		<link>http://whathecode.wordpress.com/2011/12/14/massive-scale-online-software-development/</link>
		<comments>http://whathecode.wordpress.com/2011/12/14/massive-scale-online-software-development/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 00:39:02 +0000</pubDate>
		<dc:creator>Steven Jeuris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Crazy Ideas]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://whathecode.wordpress.com/?p=945</guid>
		<description><![CDATA[Cutting right to the chase: Would it be possible to create software, entirely developed and moderated by an open community? Call it democratic software development, or open source on steroids if you will. While discussing this the default answer I usually get is &#8220;it can&#8217;t be done&#8221;, which is why I gladly filed this post [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=945&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Cutting right to the chase: <strong>Would it be possible to create software, entirely developed and moderated by an <em>open</em> community?</strong></p>
<p>Call it democratic software development, or open source on steroids if you will. While discussing this the default answer I usually get is <em>&#8220;it can&#8217;t be done&#8221;</em>, which is why I gladly filed this post under the newly created category <strong>&#8220;Crazy Ideas&#8221;</strong>. Nevertheless, I find it a valuable exercise to discuss any nutcase ideas, in order to evaluate how far-fetched they actually are.</p>
<blockquote><p>A person with a new idea is a crank until the idea succeeds. &#8211; <a href="http://en.wikipedia.org/wiki/Mark_Twain">Mark Twain</a></p></blockquote>
<p>So what would such a system look like? What would be some of the <strong>requirements</strong>?</p>
<p><strong>Easily accessible.</strong><br />
And when I say <em>easy</em>, I mean it. You shouldn&#8217;t have to download the repository first. You shouldn&#8217;t have to set up a development environment. It should run as a <strong>web service</strong> on the cloud (more buzzwords coming up!). A user account and an internet connection is all you need to get going.</p>
<p><strong>Motivate people to participate.</strong><br />
<strong></strong>Ever heard of <a href="http://en.wikipedia.org/wiki/Gamification">gamification</a>?<em> &#8220;Gamification is the use of game design techniques and mechanics to solve problems and engage audiences.&#8221; </em>If you are a software developer, chances are you ended up on <a href="http://stackoverflow.com/">Stack Overflow</a> at some point. It&#8217;s a Q&amp;A site for programmers which is quickly becoming one of the main resources for help for professional programmers. Stack Overflow incorporates many aspects of gamification, and it&#8217;s mere existence shows the power of it. A significant amount of developers is prepared to share and learn in this fun environment. Quality content is pushed to the top via a voting system, while erroneous posts are addressed by the community.</p>
<p><strong>Divide work in small enough tasks.</strong><br />
The key to dividing work across many people is to divide it in such a way that any person only has to implement one small aspect of it at a time. Traditional software development where somebody develops a feature from a to z won&#8217;t work. One programming paradigm which at first sight seems extremely suitable for this is <a href="http://en.wikipedia.org/wiki/Functional_programming">functional programming</a>. A person could implement functions, and <strong>define new functions on which he relies</strong>. Combining this with aspects from <a href="http://en.wikipedia.org/wiki/Test-driven_development">test driven development</a> where the caller has to comment and write tests for the desired function would result in <strong>automated testing</strong>.</p>
<p>Without worrying about the specifics too much (it&#8217;s just a nutcase idea after all) consider what the possibilities would be. In <a href="http://www.ted.com/talks/luis_von_ahn_massive_scale_online_collaboration.html">Luis von Ahn&#8217;s great TED talk</a> the <a href="http://en.wikipedia.org/wiki/CAPTCHA">CAPTCHA</a> inventor discusses how he re-purposed CAPTCHA in order to digitize books. Around 2,5 million books a year can be digitized through this massive-scale collaborative effort. Their next project indicates this doesn&#8217;t have to be limited to really mundane tasks. They are now <a href="http://duolingo.com/">working on translating the web</a>!</p>
<p><strong>Moderation guided by conventions.</strong><br />
Conventions are important in a group effort. Unfortunately, when discussing programming conventions <a href="http://programmers.stackexchange.com/search?q=convention">people most often discuss naming and formatting conventions</a>, while there are plenty of other important conventions to agree on. This will most likely be the topic of one of my future posts. Conventions should be as unambiguous as possible in order to know where to expect a certain piece of code, or where to place it. Conventions like these could be agreed upon through a democratic process, which seems to be working pretty well for <a href="http://meta.stackoverflow.com/faq">Stack Overflow through its meta site</a>. This allows for community moderation following the guidelines <em>established by</em> the community.</p>
<p><strong>Couple all the separate work together into one entity.</strong><br />
Going from a set of loosely coupled functions to a working library would result in plenty of extra challenges, but also opportunities. Since nobody wants an all encompassing library just to use part of its functionality, the system should allow you to extract just the functionality you are interested in.</p>
<h2>Beyond the idea</h2>
<p>Well, &#8230; I went a bit further and <a href="http://area51.stackexchange.com/proposals/36504/extension-methods">attempted to start a small proof of concept</a>. I figured the <a href="http://stackexchange.com/">Stack Exchange platform</a> on which Stack Overflow runs already encompasses much of the desired functionality, and creating a small scale library on it would be possible.  The idea was to create an <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> library for C#, which exists primarily out of a set of functions. Requesting new Stack Exchange sites is possible through <a href="http://area51.stackexchange.com/">Area 51</a>. Not unexpectedly, <a href="http://discuss.area51.stackexchange.com/a/3429/32507">my idea got shot down</a> since it doesn&#8217;t fit the intended Q&amp;A format. Oh well, &#8230; one can only try.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whathecode.wordpress.com/945/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whathecode.wordpress.com/945/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whathecode.wordpress.com/945/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whathecode.wordpress.com/945/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whathecode.wordpress.com/945/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whathecode.wordpress.com/945/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whathecode.wordpress.com/945/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whathecode.wordpress.com/945/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whathecode.wordpress.com/945/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whathecode.wordpress.com/945/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whathecode.wordpress.com/945/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whathecode.wordpress.com/945/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whathecode.wordpress.com/945/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whathecode.wordpress.com/945/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=945&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whathecode.wordpress.com/2011/12/14/massive-scale-online-software-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2648f806f3af808a2ed537c8e745558e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">whathecode</media:title>
		</media:content>
	</item>
		<item>
		<title>The code formatting fallacy</title>
		<link>http://whathecode.wordpress.com/2011/11/13/the-code-formatting-fallacy/</link>
		<comments>http://whathecode.wordpress.com/2011/11/13/the-code-formatting-fallacy/#comments</comments>
		<pubDate>Sun, 13 Nov 2011 01:58:38 +0000</pubDate>
		<dc:creator>Steven Jeuris</dc:creator>
				<category><![CDATA[LOP]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://whathecode.wordpress.com/?p=911</guid>
		<description><![CDATA[Time to stir my category cloud on the right a bit, and publish a post under a category I&#8217;ve so far only used once. Hopefully it will become clear what Language Oriented Programming (LOP) has got to do with code formatting after this post. There are several holy wars on code formatting: CamelCase vs underscores. My most [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=911&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Time to stir my category cloud on the right a bit, and publish a post under a category I&#8217;ve so far only used once. Hopefully it will become clear what <a href="http://en.wikipedia.org/wiki/Language-oriented_programming">Language Oriented Programming</a> (LOP) has got to do with code formatting after this post.</p>
<p>There are several <strong>holy wars on code formatting</strong>:</p>
<ul>
<li><a href="http://programmers.stackexchange.com/q/27264/15464">CamelCase vs underscores</a>. My most popular post is <a href="http://whathecode.wordpress.com/2011/02/10/camelcase-vs-underscores-scientific-showdown/">a review of a scientific paper</a> on the subject.</li>
<li><a href="http://programmers.stackexchange.com/q/64449/15464">How long a function should be</a>, on which I wrote <a href="http://whathecode.wordpress.com/2010/12/07/function-hell/">a somewhat controversial opinion</a>.</li>
<li>Functions should <a href="http://programmers.stackexchange.com/q/118703/15464">only have one return</a>.</li>
<li><a href="http://programmers.stackexchange.com/q/57/15464">Tabs vs spaces</a>.</li>
<li><a href="http://programmers.stackexchange.com/q/51307/15464">Self documenting code vs comments</a>.</li>
<li>The order in which to lay out members in a class.</li>
</ul>
<div>&#8230; and  <a href="http://programmers.stackexchange.com/questions/tagged/coding-standards">many more</a>.</div>
<p>All these wars are about how <strong>text</strong> should be formatted. The very notion of code being text is so ingrained in programmers, that they often can&#8217;t think outside the box. What if the <strong>actual problem is code being text</strong>?</p>
<blockquote><p>The problem is that <strong>text editors are stupid</strong> and don&#8217;t know how to work with the underlying graph structure of programs. But with the right tools, the editor could work directly with the graph structure, and give us freedom to <strong>use any visual representation</strong> we like in the editor. - <a href="http://www.sergeydmitriev.com/">Sergey Dmitriev</a>, cofounder and CEO of <a href="http://www.jetbrains.com/">JetBrains Inc</a>.</p></blockquote>
<p>This is just one of many interesting statements in <a href="http://www.onboard.jetbrains.com/is1/articles/04/10/lop/index.html">the must-read article by Sergey introducing LOP</a>. Once you consider the possibility of separating code and it&#8217;s representation, most of the <strong>code formatting discussions become obsolete</strong>.</p>
<ul>
<li>Identifiers can contain spaces, or can be represented differently based on preferences. Heck, they could be icons in a diagram.</li>
<li>Visually separating a piece of code for readability would be possible without having to split into smaller functions.</li>
<li>Multiple exit points of a function can be visualized in a diagram.</li>
</ul>
<p>&#8230; and you can think of many more.</p>
<p>Modern IDEs like Visual Studio are slowly adopting alternate visualizations for code made possible <a href="http://visualstudiogallery.msdn.microsoft.com/">by using extensions</a>. As useful as some of these extensions are, they inherit the limitations of having to work on top of text.</p>
<p>If the progress on <a href="http://www.jetbrains.com/mps/">JetBrain&#8217;s Meta Programming System</a> (MPS) is any indication of how feasible LOP will be in the future, my guess is we will be hearing a lot more from this paradigm in the years to come. A new actionscript editor, <a href="http://www.realaxy.com/editor/index">Realaxy</a>, seems to be more than capable of competing with existing editors, and is <a href="http://www.realaxy.com/revolution/index">built entirely on top of MPS</a>.</p>
<p>UPDATE: Markus Voelter <a href="http://voelterblog.blogspot.com/2011/12/mbeddr-c-early-access-preview-of.html">announced mbeddr on his blog</a>, the C language made extensible thanks to MPS.</p>
<p>Like me you might not have time to try out MPS properly, but I can highly recommend <a href="http://blogs.jetbrains.com/mps/">subscribing to their blog</a>. New screencasts are appearing at a regular basis, showcasing features ranging from implementing new language keywords to creating a visual editor for a state machine.</p>
<p><a href="http://whathecode.files.wordpress.com/2011/11/statemachineeditor.png"><img class="aligncenter size-full wp-image-938" title="State machine editor" src="http://whathecode.files.wordpress.com/2011/11/statemachineeditor.png?w=620" alt=""   /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whathecode.wordpress.com/911/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whathecode.wordpress.com/911/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whathecode.wordpress.com/911/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whathecode.wordpress.com/911/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whathecode.wordpress.com/911/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whathecode.wordpress.com/911/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whathecode.wordpress.com/911/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whathecode.wordpress.com/911/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whathecode.wordpress.com/911/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whathecode.wordpress.com/911/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whathecode.wordpress.com/911/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whathecode.wordpress.com/911/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whathecode.wordpress.com/911/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whathecode.wordpress.com/911/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=911&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whathecode.wordpress.com/2011/11/13/the-code-formatting-fallacy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2648f806f3af808a2ed537c8e745558e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">whathecode</media:title>
		</media:content>

		<media:content url="http://whathecode.files.wordpress.com/2011/11/statemachineeditor.png" medium="image">
			<media:title type="html">State machine editor</media:title>
		</media:content>
	</item>
		<item>
		<title>List of Tuples</title>
		<link>http://whathecode.wordpress.com/2011/11/03/list-of-tuples/</link>
		<comments>http://whathecode.wordpress.com/2011/11/03/list-of-tuples/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 21:27:48 +0000</pubDate>
		<dc:creator>Steven Jeuris</dc:creator>
				<category><![CDATA[.NET]]></category>

		<guid isPermaLink="false">http://whathecode.wordpress.com/?p=905</guid>
		<description><![CDATA[I still had a few posts which I was planning to write about first, but the simplicity and usefulness of the following discovery prompted me to go ahead and cut in line of my post queue. .NET 4.0 introduced a set of very interesting new data structures, called tuples. They allow you to easily group [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=905&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I still had a few posts which I was planning to write about first, but the simplicity and usefulness of the following discovery prompted me to go ahead and cut in line of my post queue.</p>
<p>.NET 4.0 introduced a set of very interesting new data structures, called <strong><a href="http://msdn.microsoft.com/en-us/library/system.tuple.aspx">tuples</a></strong>. They allow you to easily <strong>group a set of strongly typed variables together</strong>, without having to create a struct or class for it. A set of easy factory methods allows you to instantiate them with ease.</p>
<p><pre class="brush: csharp;">
// The following is a Tuple&lt;int, string&gt;.
var data = Tuple.Create( 1, &quot;apple&quot; );
</pre></p>
<p>Now how do you go about creating <strong>a list of them</strong>? Initially I attempted an approach as follows, which made my <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> brain hurt.</p>
<p><pre class="brush: csharp;">
var groceryList = new List&lt;Tuple&lt;int, string&gt;&gt;
{
    Tuple.Create( 1, &quot;kiwi&quot; ),
    Tuple.Create( 5, &quot;apples&quot; ),
    Tuple.Create( 3, &quot;potatoes&quot; ),
    Tuple.Create( 1, &quot;tomato&quot; )
};
</pre></p>
<p>When <em><a href="http://msdn.microsoft.com/en-us/library/xfhwa508.aspx">Dictionary</a></em> has <a href="http://msdn.microsoft.com/en-us/library/bb531208.aspx">such a nice initializer</a>, why can&#8217;t we? Well, we can!</p>
<p>The <em>{ }</em> syntax of the <a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx">collection initializer</a> works on any <em>IEnumerable</em> type which has an <em>Add </em>method with the correct amount of arguments<em>.</em> Without bothering how that works under the covers, that means you can simply extend from <em>List&lt;T&gt;, </em>add a custom <em>Add</em> method to initialize your <em>T, </em>and you are done! Here we go &#8230;</p>
<p><pre class="brush: csharp;">
public class TupleList&lt;T1, T2&gt; : List&lt;Tuple&lt;T1, T2&gt;&gt;
{
    public void Add( T1 item, T2 item2 )
    {
        Add( new Tuple&lt;T1, T2&gt;( item, item2 ) );
    }
}
</pre></p>
<p>&#8230; and you have your easily initializable list of tuples!</p>
<p><pre class="brush: csharp;">
var groceryList = new TupleList&lt;int, string&gt;
{
    { 1, &quot;kiwi&quot; },
    { 5, &quot;apples&quot; },
    { 3, &quot;potatoes&quot; },
    { 1, &quot;tomato&quot; }
};
</pre></p>
<p>If that doesn&#8217;t make you want to scroll over your existing codebase and start refactoring, this blog probably isn&#8217;t for you. <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whathecode.wordpress.com/905/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whathecode.wordpress.com/905/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whathecode.wordpress.com/905/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whathecode.wordpress.com/905/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whathecode.wordpress.com/905/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whathecode.wordpress.com/905/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whathecode.wordpress.com/905/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whathecode.wordpress.com/905/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whathecode.wordpress.com/905/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whathecode.wordpress.com/905/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whathecode.wordpress.com/905/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whathecode.wordpress.com/905/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whathecode.wordpress.com/905/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whathecode.wordpress.com/905/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=905&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whathecode.wordpress.com/2011/11/03/list-of-tuples/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2648f806f3af808a2ed537c8e745558e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">whathecode</media:title>
		</media:content>
	</item>
		<item>
		<title>Attribute metabehavior</title>
		<link>http://whathecode.wordpress.com/2011/09/22/attribute-metabehavior/</link>
		<comments>http://whathecode.wordpress.com/2011/09/22/attribute-metabehavior/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 18:55:17 +0000</pubDate>
		<dc:creator>Steven Jeuris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://whathecode.wordpress.com/?p=876</guid>
		<description><![CDATA[Attributes in .NET can be used to add metadata to language elements. In combination with reflection they can be put to use in plenty of powerful scenarios. A separate parser can process the data added and act upon the annotations in any way desired. A common example of this is a serializer which knows how [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=876&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx">Attributes</a> in .NET can be used to add <strong>metadata</strong> to language elements. In combination with <a href="http://msdn.microsoft.com/en-us/library/f7ykdhsy(v=VS.100).aspx">reflection</a> they can be put to use in plenty of powerful scenarios. A separate <strong>parser</strong> can process the data added and <strong>act upon the annotations</strong> in any way desired. A common example of this is a serializer which knows how to serialize an instance of a class based on attributes applied to its members. E.g. a <em><a href="http://msdn.microsoft.com/en-us/library/system.nonserializedattribute.aspx">NonSerialized</a></em> attribute determines the member doesn&#8217;t need to be serialized.</p>
<p>In <a href="http://whathecode.wordpress.com/2011/09/22/aspect-powered-wpf/">my previous post</a> I promised I would show some interesting scenarios where the mandatory enum values in my solution, needed to identify different <a href="http://msdn.microsoft.com/en-us/library/ms752914.aspx">dependency properties</a> (DPs), can be put to good use. It is not required to grasp the entire subject previously discussed, but it does help to know about DPs and their capabilities. Simply put, they are <strong>special properties</strong> (used by <a href="http://msdn.microsoft.com/en-us/library/ms752059.aspx">XAML</a>) which can notify whenever they are changed, allowing to bind other data to them. They can also be validated (check whether a value assigned to them is valid or not) and coerced (adjusting the value so it satisfies a certain condition). I consider these capabilities to be <strong>metadata</strong>, <strong>describing particular behavior</strong> associated with a given property. After extensive tinkering I found a way to express this behavior in an attribute, but it wasn&#8217;t easy. Ordinarily WPF requires you <a href="http://msdn.microsoft.com/en-us/library/ms745795.aspx">to pass callback methods along</a> when &#8216;registering&#8217; the DPs, which implement the desired behavior.</p>
<p>Two solutions can be considered:</p>
<ol>
<li><strong>The parser knows how to interpret</strong> the metadata and acts accordingly.</li>
<li>The <strong>attribute implements the actual behavior itself</strong>, and is simply called by the parser.</li>
</ol>
<p>Solution 1 is the easiest to implement, and is how attributes are used most often. <strong>Solution 2</strong> however has a <strong>great added benefit</strong>. It allows you to apply the <strong><a href="http://en.wikipedia.org/wiki/Strategy_pattern">strategy pattern</a>. </strong>Unlike solution 1, the parser doesn&#8217;t need to know about the specific implementation, but only the interface. Additional behaviors can be implemented and used without having to modify the parser. In contrast to simple metadata, an actual behavior is attached, hence I am dubbing this <strong>metabehavior</strong>. I will discuss the loopholes you have to jump through to achieve this in a next post. For now, consider the following examples to see how it could be used.</p>
<p>A regular expression <strong>validation</strong> of a dependency property can be used as follows:</p>
<p><pre class="brush: csharp;">
[DependencyProperty( Property.RegexValidation, DefaultValue = &quot;test&quot; )]
[RegexValidation( &quot;test&quot; )]
public string RegexValidation { get; set; }
</pre></p>
<p><strong>Coercing a value</strong> within a certain range, defined by two other properties can be used as follows:</p>
<p><pre class="brush: csharp;">
[DependencyProperty( Property.StartRange, DefaultValue = 0 )]
public int StartRange { get; set; }

[DependencyProperty( Property.EndRange, DefaultValue = 100 )]
public int EndRange { get; set; }

[DependencyProperty( Property.CurrentValue )]
[RangeCoercion( typeof( int ), Property.StartRange, Property.EndRange )]
public int CurrentValue { get; set; }
</pre></p>
<p>The greatest thing about all this, is that <strong>new behaviors can be implemented</strong> by extending from <em><a href="https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.PresentationFramework/Windows/DependencyPropertyFactory/Attributes/Validators/ValidationHandlerAttribute.cs">ValidationHandlerAttribute</a></em> and <em><a href="https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.PresentationFramework/Windows/DependencyPropertyFactory/Attributes/Coercion/CoercionHandlerAttribute.cs">CoercionHandlerAttribute</a></em> respectively, albeit with some added complexities due to the limitations of attributes which I will discuss later.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whathecode.wordpress.com/876/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whathecode.wordpress.com/876/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whathecode.wordpress.com/876/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whathecode.wordpress.com/876/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whathecode.wordpress.com/876/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whathecode.wordpress.com/876/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whathecode.wordpress.com/876/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whathecode.wordpress.com/876/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whathecode.wordpress.com/876/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whathecode.wordpress.com/876/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whathecode.wordpress.com/876/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whathecode.wordpress.com/876/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whathecode.wordpress.com/876/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whathecode.wordpress.com/876/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=876&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whathecode.wordpress.com/2011/09/22/attribute-metabehavior/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2648f806f3af808a2ed537c8e745558e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">whathecode</media:title>
		</media:content>
	</item>
		<item>
		<title>Aspect powered WPF</title>
		<link>http://whathecode.wordpress.com/2011/09/22/aspect-powered-wpf/</link>
		<comments>http://whathecode.wordpress.com/2011/09/22/aspect-powered-wpf/#comments</comments>
		<pubDate>Wed, 21 Sep 2011 22:51:16 +0000</pubDate>
		<dc:creator>Steven Jeuris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[PostSharp]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://whathecode.wordpress.com/?p=836</guid>
		<description><![CDATA[In some of my first posts &#8211; as it turns out I can almost celebrate one year of blogging! &#8211; I wrote about a factory approach to solve the complexities and overhead of creating dependency properties (DPs) for a WPF control; and notify properties and commands for a viewmodel. Both are essential parts when using [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=836&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In some of my first posts &#8211; as it turns out I can almost celebrate one year of blogging! &#8211; I wrote about a <strong>factory approach</strong> to solve the complexities and overhead <a href="http://whathecode.wordpress.com/2010/10/28/dependency-property-factory-part-3/">of creating dependency properties (DPs) for a WPF control</a>; and <a href="http://whathecode.wordpress.com/2010/11/15/viewmodel-property-and-command-factory/">notify properties and commands for a viewmodel</a>. Both are essential parts when using <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx">WPF</a> and following the <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">MVVM pattern</a>. <strong>To summarize</strong>: the approach was basically to delegate the creation of these complex components to a factory contained within the class which uses annotations on fields (attributes) to clarify what should be created. To create DPs, this looked as follows:</p>
<p><pre class="brush: csharp;">
public class HelloWorldControl : UserControl
{
    [Flags]
    public enum Properties
    {
        Hello,
        World
    {

    static readonly DependencyPropertyFactory&lt;Properties&gt; PropertyFactory
        = new DependencyPropertyFactory&lt;Properties&gt;( false );

    [DependencyProperty( Properties.Hello )]
    public string Hello
    {
        get { return (string)PropertyFactory.GetValue( this, Properties.Hello ); }
        set { PropertyFactory.SetValue( this, Properties.Hello, value ); }
    }

    [DependencyProperty( Properties.World )]
    public string World
    {
        get { return (string)PropertyFactory.GetValue( this, Properties.World); }
        set { PropertyFactory.SetValue( this, Properties.World, value ); }
    }
}
</pre></p>
<p>Nice and concise, but <a href="http://whathecode.wordpress.com/2010/10/28/dependency-property-factory-part-3/">as mentioned in my conclusion</a> there is still room for improvement:</p>
<ul>
<li>Requirement of an enum.</li>
<li><strong>Having to manually add the factory to the class.</strong></li>
<li><strong>Every property has almost the exact same implementation.</strong></li>
</ul>
<p>As it turns out, <a href="http://www.sharpcrafters.com/">PostSharp</a> is the perfect candidate to leverage the concept of <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming">Aspect Oriented Programming (AOP)</a> to solve the last two problems, resulting in the following solution:</p>
<p><pre class="brush: csharp;">
[WpfControl( typeof( Properties ) )]
public class HelloWorldControl : UserControl
{
    [Flags]
    public enum Properties
    {
        Hello,
        World
    {

    [DependencyProperty( Properties.Hello )]
    public string Hello { get; set; }

    [DependencyProperty( Properties.World )]
    public string World { get; set; }
}
</pre></p>
<p><strong>Where does the magic happen?</strong></p>
<p>Simply put, PostSharp does a <strong>post-compilation</strong> step, inserting the required code where needed. Which code needs to be inserted where is determined by applying <strong>aspects</strong> (exposed as attributes) to the relevant elements. The <em><a href="https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.PresentationFramework.Aspects/Windows/DependencyPropertyFactory/Aspects/WpfControlAttribute.cs">WpfControlAttribute</a></em> in the example above applies an aspect to <em>HelloWorldControl</em>. PostSharp makes it relatively easy by allowing you to implement these aspects by using plain C# classes. It&#8217;s a mature framework with an extensive feature set as will become evident from the following more in-depth description.</p>
<p>A core used feature in the implementation is the ability to <strong>dynamically &#8216;provide&#8217; aspects</strong> to the elements of your choice. The solution actually is composed of 2 aspects, <em>WpfControlAspect</em> and <em>DependencyPropertyAspect</em>, being applied to the user control and the dependency properties respectively.</p>
<ol>
<li>The <em>WpfControlAttribute</em> is actually an <em><a href="http://doc.sharpcrafters.com/postsharp-2.0/##PostSharp-2.0.chm/html/T_PostSharp_Aspects_IAspectProvider.htm">IAspectProvider</a></em>, creating a <em><a href="https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.PresentationFramework.Aspects/Windows/DependencyPropertyFactory/Aspects/WpfControlAspect.cs">WpfControlAspect</a></em> and applying it to its target (<em>HelloWorldControl</em> in the example). This extra step is only required for <strong>generic aspects</strong> as a workaround since C# doesn&#8217;t support generic attributes. The generic type arguments are passed as an argument to the attribute, and reflection is used to instantiate the actual generic aspect.</li>
<li>The <em>WpfControlAspect</em> <strong>introduces the factory</strong> into the user control, and in its turn provides a <em><a href="https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.PresentationFramework.Aspects/Windows/DependencyPropertyFactory/Aspects/DependencyPropertyAspect.cs">DependencyPropertyAspect</a></em> to all members which have the <em>DependencyPropertyAttribute</em> applied to them.</li>
<li>The aspects applied to the properties <strong>create the correct call</strong> to the <em>DependencyPropertyFactory</em>, where the actual logic is implemented.</li>
</ol>
<p>This solution represents a personal guideline I prefer to follow when writing aspects.</p>
<blockquote><p>Only resort to using aspects after applying encapsulation to its fullest extent.</p></blockquote>
<p>It&#8217;s a gut feeling I have, and I can&#8217;t quite formulate thorough arguments for it yet. When I can, I&#8217;ll be sure to write about it! Perhaps the main advantage is you are less dependant on aspects, and let&#8217;s face it, <strong>minimizing dependencies</strong> is almost always a good thing. Basically I prefer to rely on .NET and its excellent debugging and testing tools as much as possible, and only use PostSharp where .NET fails to satisfy my <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a> needs.</p>
<p><strong>Why still use enums?</strong></p>
<p>As <a href="http://whathecode.wordpress.com/2010/10/28/dependency-property-factory-part-3/">explained before</a>, they are a necessary replacement to <strong>identify the associated element</strong> which is created. They aren&#8217;t all that bad. As I will demonstrate in a next post, the enums can even be put to use in some interesting use cases. If you can&#8217;t wait, all source code and <a href="https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.PresentationFramework.Aspects.Tests/Windows/DependencyPropertyFactory/Attributes/CoercionHandlersTest.cs">a particularly interesting unit test</a> is already available for you to try out. If you haven&#8217;t installed PostSharp 2.1 RC2 or higher yet, you will need it! Actually I already discussed another use case in <a href="http://whathecode.wordpress.com/2010/11/15/viewmodel-property-and-command-factory/">a previous post</a>: binding from XAML to a command in the viewmodel by using a custom &#8216;<em>CommandBinding</em>&#8216; markup extension and passing the enum as a parameter.</p>
<p>It could be worthwhile to investigate an opt-in approach where only those elements which need to be identified from elsewhere need to be assigned an ID. At first sight it looks like the <a href="http://stackoverflow.com/questions/1235617/how-to-pass-objects-into-an-attribute-constructor/1235690#1235690">limitations for attribute arguments</a> are a big deal breaker.</p>
<p><strong>You&#8217;re breaking the conventions!</strong></p>
<p>The only convention I am still breaking is that I&#8217;m not adding the <em>DependencyProperty</em> fields<em>. </em>As <a href="http://whathecode.wordpress.com/2010/10/25/dependency-property-factory-part-2/">discussed before</a>, I see no need why these are required. The sole stated problem is that tools could rely on this convention to access the properties. Opening <a href="https://github.com/Whathecode/Framework-Class-Library-Extension/tree/master/BlendCompatibilityTest">a simple user control</a> enhanced with aspect goodiness shows that both<strong> Blend and the Visual Studio designer work as expected</strong>. That&#8217;s good enough for me!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whathecode.wordpress.com/836/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whathecode.wordpress.com/836/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whathecode.wordpress.com/836/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whathecode.wordpress.com/836/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whathecode.wordpress.com/836/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whathecode.wordpress.com/836/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whathecode.wordpress.com/836/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whathecode.wordpress.com/836/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whathecode.wordpress.com/836/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whathecode.wordpress.com/836/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whathecode.wordpress.com/836/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whathecode.wordpress.com/836/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whathecode.wordpress.com/836/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whathecode.wordpress.com/836/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=836&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whathecode.wordpress.com/2011/09/22/aspect-powered-wpf/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2648f806f3af808a2ed537c8e745558e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">whathecode</media:title>
		</media:content>
	</item>
		<item>
		<title>Casting to less generic types</title>
		<link>http://whathecode.wordpress.com/2011/07/02/casting-to-less-generic-types/</link>
		<comments>http://whathecode.wordpress.com/2011/07/02/casting-to-less-generic-types/#comments</comments>
		<pubDate>Sat, 02 Jul 2011 00:09:55 +0000</pubDate>
		<dc:creator>Steven Jeuris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Emit]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://whathecode.wordpress.com/?p=801</guid>
		<description><![CDATA[&#8230; because yes, there are valid use cases for it! Finally I found the time to write some unit tests, followed by fixing the remaining bugs, and am now excited to report on the result which effectively allows you to break type safety for generic interfaces, if you so please. Previously I discussed the variance limitations for generics, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=801&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>&#8230; because yes, there are <strong>valid use cases</strong> for it! Finally I found the time to write some unit tests, followed by fixing the remaining bugs, and am now excited to report on the result which effectively allows you to <strong>break type safety for generic interfaces, </strong>if you so please<strong>. </strong>Previously I discussed the <a href="http://whathecode.wordpress.com/2011/05/23/casting-generic-types/">variance limitations</a> for generics, and how to <a href="http://whathecode.wordpress.com/2011/05/25/creating-delegates-during-reflection-for-unknown-types/">create delegates which overcome those limitations</a>. Along the same lines I will now demonstrate how to <strong>overcome those limitations for entire generic interfaces.</strong></p>
<p>Consider the following interface which is used to check whether a certain value is valid or not.</p>
<p><pre class="brush: csharp;">
public interface IValidation&lt;in T&gt;
{
    bool IsValid( T value );
}
</pre></p>
<p>Notice how <em>T</em> is made contravariant by using the <em>in</em> keyword? Not only values of type <em>T</em> can be validated, but also any extended type. This recent feature of C# won&#8217;t help a bit in the following scenario however. <strong>During reflection </strong>you can only use this interface <strong>when you know the complete type</strong>, including the generic type parameters. In order to support any type, <strong>you would have to check for any possible type</strong> and cast to the correct corresponding interface.</p>
<p><pre class="brush: csharp;">
object validator;  // An object known to implement IValidation&lt;T&gt;
object toValidate; // The object which can be validated by using the validator.

if ( validator is IValidation&lt;string&gt; )
{
    IValidation&lt;string&gt; validation = (IValidation&lt;string&gt;)validator;
    validation.IsValid( (string)toValidate );
}
else if ( validator is IValidation&lt;int&gt; )
{
    IValidation&lt;int&gt; validation = (IValidation&lt;int&gt;)validator;
    validation.IsValid( (int)toValidate );
}
else if ...
</pre></p>
<p>Hardly entertaining, nor maintainable. What we actually need is covariance in <em>T</em>, or at least something that looks like it. We want to<strong> treat a more concrete <em>IValidation&lt;T&gt;</em> as <em>IValidation&lt;object&gt;</em></strong>. For perfectly good reasons covariance is only possible when the type parameter is only used as output, otherwise objects of the wrong type could be passed. In the given scenario however, where <strong>we know only the correct type will ever be passed, </strong>this shouldn&#8217;t be a problem.</p>
<p>The solution is using <strong>a proxy class</strong> which implements our less generic interface and delegates all calls to the actual instance, doing the required casts where necessary.</p>
<p><pre class="brush: csharp;">
public class LessGenericProxy : IValidation&lt;object&gt;
{
    readonly IValidation&lt;string&gt; _toWrap;

    public LessGenericProxy( IValidation&lt;string&gt; toWrap )
    {
        _toWrap = toWrap;
    }

    public bool IsValid( object value )
    {
        return _toWrap.IsValid( (string)value );
    }
}
</pre></p>
<p>With the power of <strong>Reflection.Emit</strong>, such classes can be <strong>generated at runtime</strong>! <a href="http://www.codeproject.com/KB/dotnet/runsharp.aspx">RunSharp</a> is a great library which makes writing Emit code feel like writing ordinary C#. It&#8217;s relatively easy (compared to using Emit) to generate the proxy class. The end result looks as follows:</p>
<p><pre class="brush: csharp;">
object validator;  // An object known to implement IValidation&lt;T&gt;
object toValidate; // The object which can be validated by using the validator.

IValidation&lt;object&gt; validation
    = Proxy.CreateGenericInterfaceWrapper&lt;IValidation&lt;object&gt;&gt;( validator );

validation.IsValid( toValidate ); // This works! No need to know about the type.

// Assuming the validator validates strings, this will throw an InvalidCastException.
//validation.IsValid( 10 );
</pre></p>
<p>Of course the <strong>proxy should be cached</strong> when used multiple times. Originally I also attempted to proxy classes instead of just interfaces by extending from them. This only works properly for virtual methods. Since non-virtual methods can&#8217;t be overridden there is no way to redirect the calls to the required inner instance.</p>
<p>Source code can be found in my library: <em><a href="https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.System/Reflection/Emit/Proxy.cs">Whathecode.System.Reflection.Emit.Proxy</a></em>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whathecode.wordpress.com/801/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whathecode.wordpress.com/801/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whathecode.wordpress.com/801/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whathecode.wordpress.com/801/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whathecode.wordpress.com/801/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whathecode.wordpress.com/801/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whathecode.wordpress.com/801/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whathecode.wordpress.com/801/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whathecode.wordpress.com/801/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whathecode.wordpress.com/801/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whathecode.wordpress.com/801/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whathecode.wordpress.com/801/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whathecode.wordpress.com/801/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whathecode.wordpress.com/801/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=801&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whathecode.wordpress.com/2011/07/02/casting-to-less-generic-types/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2648f806f3af808a2ed537c8e745558e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">whathecode</media:title>
		</media:content>
	</item>
		<item>
		<title>Beyond private accessibility</title>
		<link>http://whathecode.wordpress.com/2011/06/13/beyond-private-accessibility/</link>
		<comments>http://whathecode.wordpress.com/2011/06/13/beyond-private-accessibility/#comments</comments>
		<pubDate>Mon, 13 Jun 2011 13:29:39 +0000</pubDate>
		<dc:creator>Steven Jeuris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://whathecode.wordpress.com/?p=704</guid>
		<description><![CDATA[Surely you know about public, protected, internal and private. They are access modifiers often used in Object-Oriented Programming which indicate from where members can be accessed. If you&#8217;ve been following this blog you might have noticed I am a big fan of encapsulation. Previously I discussed how anonymous functions can be used to encapsulate reuseable [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=704&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Surely you know about <strong>public</strong>, <strong>protected</strong>, <strong>internal</strong> and <strong>private</strong>. They are <a href="http://msdn.microsoft.com/en-us/library/wxh6fsc7%28v=vs.71%29.aspx">access modifiers</a> often used in Object-Oriented Programming which indicate from where members can be accessed. If you&#8217;ve been following this blog you might have noticed I am <a href="/2011/06/05/improved-encapsulation-using-lambdas/">a big fan of <strong>encapsulation</strong></a>. Previously I discussed how anonymous functions can be used to <strong>encapsulate reuseable logic within the scope of one function</strong>. This inspired me to look for more ways in which lambdas can be used for improved encapsulation.</p>
<blockquote><p>Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared. &#8211; <a href="http://msdn.microsoft.com/en-us/library/st6sy9xe%28v=vs.71%29.aspx">msdn (.NET)</a></p></blockquote>
<p>Some languages go a step further and support <strong><a href="http://en.wikipedia.org/wiki/Local_variable" rel="nofollow">static locals</a></strong>, which allow a value to be retained from one call of a function to another<strong> with a <a href="http://en.wikipedia.org/wiki/Static_variable">static lifetime</a></strong>. The variable can only be accessed from within the function scope where it is declared. I have <a href="http://programmers.stackexchange.com/q/82047/15464">yet to find a language which supports the same, but with<strong> instance lifetime</strong></a>. Such a variable <strong>would only be visible to a single method within a single instance</strong>.</p>
<h2>Function private?</h2>
<p>Let&#8217;s call such a hypothetical accessibility &#8216;function private&#8217;. When would you use it? Consider those annoying <a href="http://io9.com/5628229/why-do-light-bulbs-burn-out-just-as-theyre-turned-on">light bulbs that burn out just as they&#8217;re turned on</a>.</p>
<div class="alignright" style="clear:right;width:230px;"><img class="center aligncenter" src="http://l.thumbs.canstockphoto.com/canstock2610771.jpg" alt="" width="150" height="107" /><br />
The <strong>_<em>lifeTime</em> variable is only relevant to the <em>SwitchOn</em> method</strong>. Notice how C# already offers a way to write the <em>IsOn</em> property in a concise way by using an <a href="http://msdn.microsoft.com/en-us/library/bb384054.aspx">auto-implemented property</a>. This actually already limits the scope of its backing field beyond private! The auto-generated backing field can only be accessed from the getter and setter.</div>
<div style="width:400px;"><pre class="brush: csharp;">
class LightBulb
{
    public bool IsOn { get; private set; }

    private int _lifeTime = 100;
    public void SwitchOn()
    {
        if ( _lifeTime - 1 &gt;= 0 )
        {
            --_lifeTime;
            IsOn = true;
        }
    }

    public void SwitchOff()
    {
        IsOn = false;
    }
}
</pre></p>
</div>
<p>What if the following would be possible? It would encapsulate <em>lifeTime</em> just to the scope where it&#8217;s needed.</p>
<p><pre class="brush: csharp;">
public void SwitchOn()
{
    private int lifeTime = 100;  // function private variable
    // private static int staticVar;  // add 'static' to create a static local

    if ( lifeTime - 1 &gt;= 0 )
    {
        --lifeTime;
        IsOn = true;
    }
}
</pre></p>
<h2>Lambda scope</h2>
<p>A <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx">lambda</a> is something peculiar. It can be used to create <a href="http://msdn.microsoft.com/en-us/library/ms173171%28v=VS.100%29.aspx">delegates</a>, but <strong>how do they work</strong>? What happens behind the scenes? I <a href="http://stackoverflow.com/q/6280656/590790">asked the question on Stack Exchange</a>, and got some really insightful answers. Relevant to this discussion are the following two points:</p>
<ul>
<li>The <em>method</em> that backs the delegate for a given lambda is always the same.</li>
<li>The <em>method</em> that backs the delegate for &#8220;the same&#8221; lambda that appears lexically twice is <em>permitted</em> to be the same, but in practice is <em>not</em> the same in .NET 4.0.</li>
</ul>
<p>The fact that every lambda has a <strong>unique backing method</strong> gives the possibility to <strong>use it as an identifier of the scope where it is defined.</strong></p>
<h2>Unsafe implementation</h2>
<p>By ab(using) this behavior I was able to create <a href="http://pastebin.com/AHuvV4wy">the following working implementation</a>. The <em>Private</em> class creates and keeps track of its instances by linking them to the delegates passed to the static constructor methods. The first time the method is called the instance is created. Subsequent calls the instance is retrieved by doing a lookup in static dictionaries based on the passed arguments.</p>
<p><pre class="brush: csharp;">
public void SwitchOn()
{
    Private&lt;int&gt; lifeTime = Private&lt;int&gt;.Instance( () =&gt; 100, this );  // function private
    // Private&lt;int&gt; staticVar = Private&lt;int&gt;.Static( () =&gt; 0 );  // static local

    if ( lifeTime.Value - 1 &gt;= 0 )
    {
        --lifeTime.Value;
        IsOn = true;
    }
}
</pre></p>
<p><strong>Why is it unsafe?</strong></p>
<ul>
<li>This behavior is <strong>not guaranteed to be supported in later versions of .NET</strong>. As mentioned before: <em>&#8220;The method that backs the delegate for &#8220;the same&#8221; lambda that appears lexically twice <strong>is permitted to be the same</strong>, but in practice is not the same in .NET 4.0.&#8221;</em></li>
<li>Objects which use the code as it is now are <strong>never garbage collected</strong>. Using <a href="http://msdn.microsoft.com/en-us/library/system.weakreference.aspx">weak references</a> could solve this issue. It seems <a href="http://blogs.msdn.com/b/nicholg/archive/2006/06/04/617466.aspx">a dictionary with weak references</a> already exists.</li>
<li>There is a small performance overhead doing the dictionary lookups. Ideally this feature would be supported at compile time.</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whathecode.wordpress.com/704/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whathecode.wordpress.com/704/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whathecode.wordpress.com/704/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whathecode.wordpress.com/704/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whathecode.wordpress.com/704/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whathecode.wordpress.com/704/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whathecode.wordpress.com/704/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whathecode.wordpress.com/704/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whathecode.wordpress.com/704/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whathecode.wordpress.com/704/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whathecode.wordpress.com/704/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whathecode.wordpress.com/704/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whathecode.wordpress.com/704/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whathecode.wordpress.com/704/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=704&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whathecode.wordpress.com/2011/06/13/beyond-private-accessibility/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2648f806f3af808a2ed537c8e745558e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">whathecode</media:title>
		</media:content>

		<media:content url="http://l.thumbs.canstockphoto.com/canstock2610771.jpg" medium="image" />
	</item>
		<item>
		<title>Improved encapsulation using lambdas</title>
		<link>http://whathecode.wordpress.com/2011/06/05/improved-encapsulation-using-lambdas/</link>
		<comments>http://whathecode.wordpress.com/2011/06/05/improved-encapsulation-using-lambdas/#comments</comments>
		<pubDate>Sun, 05 Jun 2011 17:42:26 +0000</pubDate>
		<dc:creator>Steven Jeuris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[OOP]]></category>
		<category><![CDATA[Software Design]]></category>

		<guid isPermaLink="false">http://whathecode.wordpress.com/?p=684</guid>
		<description><![CDATA[Let&#8217;s take a sidestep from the more advanced runtime code generation topic (don&#8217;t worry, still more to follow later) and move to easier territory. On a blog about software design, what better topic than encapsulation. Abstraction, information hiding, and encapsulation are very different, but highly-related, concepts. One could argue that abstraction is a technique that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=684&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s take a sidestep from the more advanced <a href="./2011/05/30/creating-delegates-during-reflection-with-unbound-instances/">runtime code generation topic</a> (don&#8217;t worry, still more to follow later) and move to easier territory. On a blog about software design, what better topic than <strong>encapsulation</strong>.</p>
<blockquote><p><strong>Abstraction</strong>, <strong>information hiding</strong>, and <strong>encapsulation</strong> are very different, but highly-related, concepts. One could argue that abstraction is a technique that helps us identify which specific information should be visible, and which information should be hidden. Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible. - <a href="http://www.itmweb.com/essay550.htm">Edward V. Berard</a></p></blockquote>
<p>Modern <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented languages</a> start to lend features from <a href="http://en.wikipedia.org/wiki/Functional_programming">functional programming languages</a>, like <strong><a href="http://en.wikipedia.org/wiki/Lambda_%28programming%29">lambdas</a></strong>. They can be used to create <a href="http://en.wikipedia.org/wiki/Anonymous_function">anonymous functions</a> using a very concise syntax. One of the often overlooked advantages of anonymous functions beside its conciseness is they can be used to <strong>encapsulate logic even further than a private method</strong>. When making a method private, it can be accessed by the entire scope of the class, while<strong> anonymous functions can only be accessed from the scope they are created in, or passed to</strong>.</p>
<p>Consider the following highly inefficient <em>&#8220;Hello World!&#8221;</em> implementation:</p>
<p><pre class="brush: csharp;">
        public void HelloWorld()
        {
            string[] words = new[] { &quot;hello&quot;, &quot;pretty&quot;, &quot;world&quot; };

            Console.WriteLine(
                ComplexHelloWorldParsing( words[ 0 ] ) +
                words[ 1 ] +
                ComplexHelloWorldParsing( words[ 2 ] ) );
        }

        private static string ComplexHelloWorldParsing( string input )
        {
            string parsed = input;
            // ... plenty of complex specific parsing, only used in HelloWorld.
            return parsed;
        }
</pre></p>
<p><em>ComplexHelloWorldParsing</em> is &#8211; and let&#8217;s assume should &#8211; only be used inside the<em> HelloWorld</em> method. Still it is <strong>visible to the entire class</strong>. In such a scenario, <strong>where encapsulating the specific behavior doesn&#8217;t make sense</strong>, I would use the following approach regardless of lines of code inside the delegate.</p>
<p><pre class="brush: csharp;">
public void HelloWorld()
{
    string[] words = new[] { &quot;hello&quot;, &quot;pretty&quot;, &quot;world&quot; };

    Func complexParsing = s =&gt;
    {
        string parsed = s;
        // ... plenty of complex method specific parsing.
        return parsed;
    };

    Console.WriteLine( complexParsing( words[ 0 ] ) + words[ 1 ] + complexParsing( words[ 2 ] ) );
}
</pre></p>
<p>It surprises me <a href="http://codereview.stackexchange.com/q/1911/2254">not all people agree on this advantage</a>. For the same reason some professional programmers <a href="/2010/12/07/function-hell/">prefer to split functions just to make them smaller</a>, some state <strong>lambdas should always be short</strong>. They state longer logic should (by a rule of thumb) be placed in a private method. If you know <strong>any pro &#8216;short delegate&#8217; arguments</strong>, be sure to let me know. I started <a href="http://programmers.stackexchange.com/q/81714/15464">a question relating to this topic</a> on Programmers Stack Exchange.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whathecode.wordpress.com/684/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whathecode.wordpress.com/684/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whathecode.wordpress.com/684/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whathecode.wordpress.com/684/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whathecode.wordpress.com/684/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whathecode.wordpress.com/684/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whathecode.wordpress.com/684/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whathecode.wordpress.com/684/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whathecode.wordpress.com/684/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whathecode.wordpress.com/684/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whathecode.wordpress.com/684/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whathecode.wordpress.com/684/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whathecode.wordpress.com/684/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whathecode.wordpress.com/684/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=684&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whathecode.wordpress.com/2011/06/05/improved-encapsulation-using-lambdas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2648f806f3af808a2ed537c8e745558e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">whathecode</media:title>
		</media:content>
	</item>
		<item>
		<title>Creating delegates during reflection with unbound instances</title>
		<link>http://whathecode.wordpress.com/2011/05/30/creating-delegates-during-reflection-with-unbound-instances/</link>
		<comments>http://whathecode.wordpress.com/2011/05/30/creating-delegates-during-reflection-with-unbound-instances/#comments</comments>
		<pubDate>Mon, 30 May 2011 14:35:14 +0000</pubDate>
		<dc:creator>Steven Jeuris</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Expression Trees]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://whathecode.wordpress.com/?p=662</guid>
		<description><![CDATA[Previously I discussed how to work around the variance limitations of the Delegate.CreateDelegate method. CreateDelegate has quite a few overloads, and acts differently based on the parameters which are passed. It also allows you to create open instance or closed static delegates. Without going into too much detail: Closed delegate: an instance is bound to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=662&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="./2011/05/25/creating-delegates-during-reflection-for-unknown-types/">Previously</a> I discussed how to work around the <a href="http://msdn.microsoft.com/en-us/library/ms228359%28v=vs.80%29.aspx">variance limitations</a> of the <a href="http://msdn.microsoft.com/en-us/library/74x8f551.aspx"><em>Delegate.CreateDelegate</em></a> method. <strong><em>CreateDelegate</em></strong> has quite a few overloads, and <strong>acts differently based on the parameters which are passed</strong>. It also allows you to create <a href="http://peisker.net/dotnet/languages2005.htm#delegatetargets"><strong>open instance or closed static delegates</strong></a>. Without going into too much detail:</p>
<ul>
<li><strong>Closed delegate</strong>: an instance is bound to the delegate along with the method. In practice this means when calling the delegate, it will always operate on the same instance.</li>
<li><strong>Open delegate</strong>: not bound to a specific target object until invocation time. An instance on which the method should operate is passed as first argument during invocation.</li>
</ul>
<p>For now, I will only discuss creating <strong>open instance delegates</strong>. These allow you to invoke an instance method, while passing a first argument, specifying the instance on which it should be invoked.</p>
<blockquote><p>Divide your programs into methods that perform one identifiable task. Keep all of the operations in a method at the same level of abstraction. &#8211; Kent Beck&#8217;s <a href="http://www.amazon.com/Smalltalk-Best-Practice-Patterns-Kent/dp/013476904X">Smalltalk Best Practice Patterns</a></p></blockquote>
<p>In an attempt to better follow this principle, better known as the <a href="http://my.safaribooksonline.com/book/software-engineering-and-development/9780596519780/practice/chp.slap">Single Level of Abstraction (SLAP) </a>principle, I&#8217;ve split up the <em>CreateDelegate</em> method into two helper methods. One to create &#8216;simple&#8217; delegates, and one to create open instance delegates. Later, an additional third method could be added to create closed static delegates.</p>
<p>By <strong>&#8216;simple&#8217; delegates</strong> I mean delegates of which the signature matches that of <em>MethodInfo</em>. More particularly, the method has the same amount of arguments than the delegate.</p>
<p><pre class="brush: csharp;">
public static TDelegate CreateDelegate&lt;TDelegate&gt;(
    MethodInfo method,
    object instance = null,
    CreateOptions options = CreateOptions.None )
    where TDelegate : class
{ ... }
</pre></p>
<p>By default, this method results in a simple<em> CreateDelegate</em> call<em>.</em> Instead of having to pass the delegate type as an argument a generic approach is used, eliminating the need to cast the returned delegate. When the <em>options</em> argument is set to <strong><em>CreateOptions.Downcasting</em></strong>, this method behaves like the<em> CreateDowncastingDelegate</em> method <a href="/2011/05/25/creating-delegates-during-reflection-for-unknown-types/">from my previous post</a>. Downcasts from the delegate argument types and return type to the required types of the method are generated where needed.</p>
<p>The helper method to <strong>create open instance delegates </strong>looks as follows:</p>
<p><pre class="brush: csharp;">
/// &lt;summary&gt;
///   Creates a delegate of a specified type that represents a method
///   which can be executed on an instance passed as parameter.
/// &lt;/summary&gt;
/// &lt;typeparam name = &quot;TDelegate&quot;&gt;
///   The type for the delegate. This delegate needs at least one (first) type parameter
///   denoting the type of the instance which will be passed.
///   E.g. Action&lt;ExampleObject, object&gt;,
///        where ExampleObject denotes the instance type and object denotes
///        the desired type of the first parameter of the method.
/// &lt;/typeparam&gt;
/// &lt;param name = &quot;method&quot;&gt;The MethodInfo describing the method of the instance type.&lt;/param&gt;
/// &lt;param name = &quot;options&quot;&gt;Options which specify what type of delegate should be created.&lt;/param&gt;
public static TDelegate CreateOpenInstanceDelegate&lt;TDelegate&gt;(
    MethodInfo method,
    CreateOptions options = CreateOptions.None )
    where TDelegate : class
    { ... }
</pre></p>
<p>The comments indicate clearly what <em>TDelegate</em> should look like. Of course, no instance can be passed, clearly specifying it needs to be specified in the delegate type. Furthermore, the passed <em>MethodInfo</em> is required to be an instance method. All these measures are meant to clarify this specific usage of <em>CreateDelegate</em>. Additionally, similar to passing <em>CreateOptions.Downcasting</em> to the other helper method, it allows you to break the variance safety of the ordinary <em>CreateDelegate</em> method.</p>
<p>Both helper functions can be found in <a href="https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.System/DelegateHelper.cs"><em>DelegateHelper.cs</em></a>. I also added <em>MethodInfo</em> extension functions to the <a href="https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.System/Reflection/Extensions/Extensions.MethodInfo.cs">reflection extensions</a>, resulting in a more concise syntax.</p>
<p>Example usage:</p>
<p><pre class="brush: csharp;">
MethodInfo toUpperMethod = typeof( string ).GetMethod( &quot;ToUpper&quot;, new Type[] { } );
Func&lt;string, string&gt; toUpper = toUpperMethod.CreateOpenInstanceDelegate&lt;Func&lt;string, string&gt;&gt;();
string upper = toUpper( &quot;test&quot; ); // Will result in &quot;TEST&quot;.
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/whathecode.wordpress.com/662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/whathecode.wordpress.com/662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/whathecode.wordpress.com/662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/whathecode.wordpress.com/662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/whathecode.wordpress.com/662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/whathecode.wordpress.com/662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/whathecode.wordpress.com/662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/whathecode.wordpress.com/662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/whathecode.wordpress.com/662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/whathecode.wordpress.com/662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/whathecode.wordpress.com/662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/whathecode.wordpress.com/662/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/whathecode.wordpress.com/662/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/whathecode.wordpress.com/662/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=whathecode.wordpress.com&amp;blog=17001023&amp;post=662&amp;subd=whathecode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://whathecode.wordpress.com/2011/05/30/creating-delegates-during-reflection-with-unbound-instances/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2648f806f3af808a2ed537c8e745558e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">whathecode</media:title>
		</media:content>
	</item>
	</channel>
</rss>
