<?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>Memetic Musings</title>
	<atom:link href="http://amitdev.in/blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://amitdev.in/blog</link>
	<description>My blog space - mainly on things technical.</description>
	<lastBuildDate>Tue, 10 Jan 2012 09:47:14 +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>Vimpy &#8211; A vim plugin to make navigation easy on python projects</title>
		<link>http://amitdev.in/blog/?p=87</link>
		<comments>http://amitdev.in/blog/?p=87#comments</comments>
		<pubDate>Thu, 22 Sep 2011 18:14:23 +0000</pubDate>
		<dc:creator>me</dc:creator>
				<category><![CDATA[Python]]></category>
		<category><![CDATA[vim]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://amitdev.in/blog/?p=87</guid>
		<description><![CDATA[Update: The post below has become obsolete with Vimpy 0.2. Now from inside vim, you just need to: Use :VimpyCreate path [exclude-path] to create index (One time operation) :VimpyLoad to load it And your index will be updated automatically as &#8230; <a href="http://amitdev.in/blog/?p=87">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><strong>Update:</strong> The post below has become obsolete with Vimpy <a href="http://www.vim.org/scripts/script.php?script_id=3752">0.2</a>. Now from inside vim, you just need to:</p>
<li> Use :VimpyCreate
<project-name> path [exclude-path] to create index (One time operation)</p>
<li> :VimpyLoad <file-name> to load it<br />
And your index will be updated automatically as long as you edit files from Vim.</p>
<p><strong>Old Post:</strong><br />
If you work on lot of python files, it may not be easy to navigate between files with vim. I tried a bunch of tools like ctags/ptags, cscope, or tips with gf etc, but I wasn&#8217;t satisfied with any of them. So I wrote this <a href="http://www.vim.org/scripts/script.php?script_id=3752">vim script</a> to make life easier. Have a look at the following video to see what it does and try it out!</p>
<p>Note: This is in alpha state and just provides basic ctags like features (hopefully in a better way). I&#8217;ll be updating this when I get time. Code is on <a href="https://github.com/amitdev/vimpy">github</a>. Do let me know your feedback in case you try it.</p>
<p>Timeline:<br />
0.0  &#8211; Installation<br />
0.25 &#8211; Creating tag/index file<br />
1.50 &#8211; Using Vimpy!</p>
<p><iframe width="425" height="349" src="http://www.youtube.com/embed/eou423LaZbw?hl=en&#038;fs=1" frameborder="0" allowfullscreen></iframe></p>
]]></content:encoded>
			<wfw:commentRss>http://amitdev.in/blog/?feed=rss2&#038;p=87</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Understanding reference cycles in Python</title>
		<link>http://amitdev.in/blog/?p=55</link>
		<comments>http://amitdev.in/blog/?p=55#comments</comments>
		<pubDate>Wed, 24 Aug 2011 18:39:16 +0000</pubDate>
		<dc:creator>me</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[debugging]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://amitdev.in/blog/?p=55</guid>
		<description><![CDATA[Introduction In Python, garbage collection is done by reference counting, which means objects get garbage collected once their references reach 0. A reference to an object is created via the assignment operation, and it can be removed by a del &#8230; <a href="http://amitdev.in/blog/?p=55">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>In Python, garbage collection is done by reference counting, which means objects get garbage collected once their references reach 0. A reference to an object is created via the assignment operation, and it can be removed by a del or automatically when the variable goes out of scope or reassigned. A simple example would be:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">a <span style="color: #66cc66;">=</span> <span style="color: #483d8b;">&quot;hello&quot;</span> &nbsp; &nbsp;<span style="color: #808080; font-style: italic;"># string object &quot;hello&quot; has refcount = 1</span><br />
b <span style="color: #66cc66;">=</span> a &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #808080; font-style: italic;"># refcount = 2</span><br />
a <span style="color: #66cc66;">=</span> A<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #808080; font-style: italic;"># refcount of &quot;hello&quot; = 1, A = 1</span><br />
a <span style="color: #66cc66;">=</span> <span style="color: #008000;">None</span> &nbsp; &nbsp; &nbsp; <span style="color: #808080; font-style: italic;"># A is gc'd</span><br />
<span style="color: #ff7700;font-weight:bold;">del</span> b &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #808080; font-style: italic;"># &quot;hello&quot; is gc'd</span></div></td></tr></tbody></table></div>
<h2>What are reference cycles anyway?</h2>
<p>If, for some reason, an object&#8217;s reference count does not reach 0, it will never be garbage collected by the above approach. How can this happen? This can happen when the reference graph (a set of objects as nodes and its references as edges) has a cycle. Again a simple example would make it clear:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">class</span> A:<br />
&nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: #66cc66;">,</span> name<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">name</span> <span style="color: #66cc66;">=</span> name<br />
&nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__repr__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #483d8b;">&quot;A [%s]&quot;</span> % <span style="color: #008000;">self</span>.<span style="color: black;">name</span><br />
a <span style="color: #66cc66;">=</span> A<span style="color: black;">&#40;</span><span style="color: #483d8b;">'a'</span><span style="color: black;">&#41;</span><br />
b <span style="color: #66cc66;">=</span> A<span style="color: black;">&#40;</span><span style="color: #483d8b;">'b'</span><span style="color: black;">&#41;</span><br />
a.<span style="color: black;">ref</span> <span style="color: #66cc66;">=</span> b<br />
b.<span style="color: black;">ref</span> <span style="color: #66cc66;">=</span> a</div></td></tr></tbody></table></div>
<p>Let&#8217;s see how its reference graph looks like:<br />
<div id="attachment_73" class="wp-caption aligncenter" style="width: 266px"><a href="http://amitdev.in/blog/wp-content/uploads/2011/08/cyc1.png"><img src="http://amitdev.in/blog/wp-content/uploads/2011/08/cyc1-256x300.png" alt="Cycle 1" title="cyc1" width="256" height="300" class="size-medium wp-image-73" /></a><p class="wp-caption-text">Simple Cycle</p></div></p>
<p>So does that mean there is no way to cleanup these objects?<br />
No.<br />
Python&#8217;s gc has a mechanism to detect these cycles and get rid of these objects. The <a href="http://docs.python.org/library/gc.html">gc module</a> provides some useful functions to interact with the garbage collection. The <em>gc.collect()</em> function can be used to invoke a full collection (which also cleans up unused objects in cycles) on demand. It is also called periodically by python based on the thresholds set using <em>set_threshold()</em>. We can also set some debug options to check which objects are stuck in a cycle using <em>set_debug()</em>. So for our example above we get the following output:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">gc</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #dc143c;">gc</span>.<span style="color: black;">set_debug</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">gc</span>.<span style="color: black;">DEBUG_SAVEALL</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #dc143c;">gc</span>.<span style="color: black;">collect</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
<span style="color: #ff4500;">8</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">pprint</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #dc143c;">pprint</span>.<span style="color: #dc143c;">pprint</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">gc</span>.<span style="color: black;">garbage</span><span style="color: black;">&#41;</span><br />
<span style="color: black;">&#91;</span>A <span style="color: black;">&#91;</span>b<span style="color: black;">&#93;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: black;">&#123;</span><span style="color: #483d8b;">'name'</span>: <span style="color: #483d8b;">'b'</span><span style="color: #66cc66;">,</span> <span style="color: #483d8b;">'ref'</span>: A <span style="color: black;">&#91;</span>a<span style="color: black;">&#93;</span><span style="color: black;">&#125;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span><span style="color: #ff7700;font-weight:bold;">class</span> <span style="color: #dc143c;">__main__</span>.<span style="color: black;">A</span> at <span style="color: #ff4500;">0x00000000029DC9E8</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;A <span style="color: black;">&#91;</span>a<span style="color: black;">&#93;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: black;">&#123;</span><span style="color: #483d8b;">'__doc__'</span>: <span style="color: #008000;">None</span><span style="color: #66cc66;">,</span><br />
&nbsp; <span style="color: #483d8b;">'__init__'</span>: <span style="color: #66cc66;">&lt;</span>function <span style="color: #0000cd;">__init__</span> at <span style="color: #ff4500;">0x0000000002B73D68</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp; <span style="color: #483d8b;">'__module__'</span>: <span style="color: #483d8b;">'__main__'</span><span style="color: #66cc66;">,</span><br />
&nbsp; <span style="color: #483d8b;">'__repr__'</span>: <span style="color: #66cc66;">&lt;</span>function <span style="color: #0000cd;">__repr__</span> at <span style="color: #ff4500;">0x0000000002B73DD8</span><span style="color: #66cc66;">&gt;</span><span style="color: black;">&#125;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: black;">&#123;</span><span style="color: #483d8b;">'name'</span>: <span style="color: #483d8b;">'a'</span><span style="color: #66cc66;">,</span> <span style="color: #483d8b;">'ref'</span>: A <span style="color: black;">&#91;</span>b<span style="color: black;">&#93;</span><span style="color: black;">&#125;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span>function <span style="color: #0000cd;">__repr__</span> at <span style="color: #ff4500;">0x0000000002B73DD8</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span>function <span style="color: #0000cd;">__init__</span> at <span style="color: #ff4500;">0x0000000002B73D68</span><span style="color: #66cc66;">&gt;</span><span style="color: black;">&#93;</span></div></td></tr></tbody></table></div>
<p>This shows the cycle (In the absence of cycles, the gc.garbage list would be empty).</p>
<p>Well, in a typical python script one need nor worry about all this because python would clean this automatically anyway. However, if you have a long running process (say a web server), it is often desirable to disable the full collection or at least to increase the delay. This is to avoid unpredictable gc pauses. In such an application, it is prudent to write code that avoids cycles. It might appear that it would be an easy thing to do. But there are various other ways in which a cycle can be introduced. Let&#8217;s look at couple of non obvious cases.</p>
<h3>Example 1</h3>
<p>Consider the following code. There is a cycle hidden in there, can you spot it?</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">class</span> C:<br />
&nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> cleanup<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">pass</span><br />
&nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #008000;">self</span>.<span style="color: black;">mycleanup</span> <span style="color: #66cc66;">=</span> <span style="color: #008000;">self</span>.<span style="color: black;">cleanup</span><br />
<br />
c <span style="color: #66cc66;">=</span> C<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></div></td></tr></tbody></table></div>
<p>Nothing obviously wrong there, so lets check if there is indeed a cycle:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> c <span style="color: #66cc66;">=</span> C<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> c <span style="color: #66cc66;">=</span> <span style="color: #008000;">None</span> <span style="color: #808080; font-style: italic;"># This should have removed C.</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #dc143c;">gc</span>.<span style="color: black;">collect</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
<span style="color: #ff4500;">3</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #dc143c;">pprint</span>.<span style="color: #dc143c;">pprint</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">gc</span>.<span style="color: black;">garbage</span><span style="color: black;">&#41;</span><br />
<span style="color: black;">&#91;</span><span style="color: black;">&#123;</span><span style="color: #483d8b;">'mycleanup'</span>: <span style="color: #66cc66;">&lt;</span>bound method C.<span style="color: black;">cleanup</span> of <span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002CAC908</span><span style="color: #66cc66;">&gt;&gt;</span><span style="color: black;">&#125;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002CAC908</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span>bound method C.<span style="color: black;">cleanup</span> of <span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002CAC908</span><span style="color: #66cc66;">&gt;&gt;,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002B9CDC8</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span><span style="color: #ff7700;font-weight:bold;">class</span> <span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> at <span style="color: #ff4500;">0x00000000029DCD58</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;<span style="color: black;">&#123;</span><span style="color: #483d8b;">'cleanup'</span>: <span style="color: #66cc66;">&lt;</span>bound method C.<span style="color: black;">nocleanup</span> of <span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002B9CDC8</span><span style="color: #66cc66;">&gt;&gt;</span><span style="color: black;">&#125;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: black;">&#123;</span><span style="color: #483d8b;">'__doc__'</span>: <span style="color: #008000;">None</span><span style="color: #66cc66;">,</span><br />
&nbsp; <span style="color: #483d8b;">'__init__'</span>: <span style="color: #66cc66;">&lt;</span>function <span style="color: #0000cd;">__init__</span> at <span style="color: #ff4500;">0x0000000002B85358</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp; <span style="color: #483d8b;">'__module__'</span>: <span style="color: #483d8b;">'__main__'</span><span style="color: #66cc66;">,</span><br />
&nbsp; <span style="color: #483d8b;">'cleanup'</span>: <span style="color: #66cc66;">&lt;</span>function cleanup at <span style="color: #ff4500;">0x0000000002B85278</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp; <span style="color: #483d8b;">'nocleanup'</span>: <span style="color: #66cc66;">&lt;</span>function nocleanup at <span style="color: #ff4500;">0x0000000002B852E8</span><span style="color: #66cc66;">&gt;</span><span style="color: black;">&#125;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span>bound method C.<span style="color: black;">nocleanup</span> of <span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002B9CDC8</span><span style="color: #66cc66;">&gt;&gt;,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span>function cleanup at <span style="color: #ff4500;">0x0000000002B85278</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span>function nocleanup at <span style="color: #ff4500;">0x0000000002B852E8</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span>function <span style="color: #0000cd;">__init__</span> at <span style="color: #ff4500;">0x0000000002B85358</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;<span style="color: black;">&#40;</span><span style="color: #008000;">False</span><span style="color: #66cc66;">,</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: black;">&#123;</span><span style="color: #483d8b;">'mycleanup'</span>: <span style="color: #66cc66;">&lt;</span>bound method C.<span style="color: black;">cleanup</span> of <span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002B69348</span><span style="color: #66cc66;">&gt;&gt;</span><span style="color: black;">&#125;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002B69348</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span>bound method C.<span style="color: black;">cleanup</span> of <span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002B69348</span><span style="color: #66cc66;">&gt;&gt;,</span><br />
&nbsp;<span style="color: black;">&#123;</span><span style="color: #483d8b;">'mycleanup'</span>: <span style="color: #66cc66;">&lt;</span>bound method C.<span style="color: black;">cleanup</span> of <span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002B691C8</span><span style="color: #66cc66;">&gt;&gt;</span><span style="color: black;">&#125;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002B691C8</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span>bound method C.<span style="color: black;">cleanup</span> of <span style="color: #66cc66;">&lt;</span><span style="color: #dc143c;">__main__</span>.<span style="color: black;">C</span> instance at <span style="color: #ff4500;">0x0000000002B691C8</span><span style="color: #66cc66;">&gt;&gt;</span><span style="color: black;">&#93;</span></div></td></tr></tbody></table></div>
<p>So there&#8217;s indeed a cycle. This is how this looks graphically:<br />
<div id="attachment_76" class="wp-caption aligncenter" style="width: 310px"><a href="http://amitdev.in/blog/wp-content/uploads/2011/08/cyc2.png"><img src="http://amitdev.in/blog/wp-content/uploads/2011/08/cyc2-300x206.png" alt="Cycle 2" title="cyc2" width="300" height="206" class="size-medium wp-image-76" /></a><p class="wp-caption-text">Bound Method Cycle</p></div></p>
<p>Here&#8217;s what happened: We created a bound method object and saved it in a variable. The bound method object stores a reference to its class which has a reference back. When you call an instance method, this bound method object is created and destroyed in the background and hence there is no issue. So if you are saving method references and passing it around, be careful.</p>
<h3>Example 2</h3>
<p>Consider the following code. Again, there is a cycle hidden in there:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">def</span> outer<span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:<br />
&nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> inner<span style="color: black;">&#40;</span>n<span style="color: black;">&#41;</span>:<br />
&nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">if</span> n <span style="color: #66cc66;">&gt;</span> <span style="color: #ff4500;">1</span>:<br />
&nbsp; &nbsp; &nbsp; inner<span style="color: black;">&#40;</span>n-<span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span><br />
<br />
outer<span style="color: black;">&#40;</span><span style="color: #ff4500;">5</span><span style="color: black;">&#41;</span><br />
<span style="color: #808080; font-style: italic;">#At this point there should not be anything left in memory.</span></div></td></tr></tbody></table></div>
<p>Lets do the <em>gc.collect()</em>:</p>
<div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #dc143c;">gc</span>.<span style="color: black;">collect</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br />
<span style="color: #66cc66;">&gt;&gt;&gt;</span> <span style="color: #dc143c;">pprint</span>.<span style="color: #dc143c;">pprint</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">gc</span>.<span style="color: black;">garbage</span><span style="color: black;">&#41;</span><br />
<span style="color: black;">&#91;</span><span style="color: #66cc66;">&lt;</span>cell at <span style="color: #ff4500;">0x00000000026D6048</span>: function <span style="color: #008000;">object</span> at <span style="color: #ff4500;">0x0000000002C9FE48</span><span style="color: #66cc66;">&gt;,</span><br />
&nbsp;<span style="color: black;">&#40;</span><span style="color: #66cc66;">&lt;</span>cell at <span style="color: #ff4500;">0x00000000026D6048</span>: function <span style="color: #008000;">object</span> at <span style="color: #ff4500;">0x0000000002C9FE48</span><span style="color: #66cc66;">&gt;,</span><span style="color: black;">&#41;</span><span style="color: #66cc66;">,</span><br />
&nbsp;<span style="color: #66cc66;">&lt;</span>function inner at <span style="color: #ff4500;">0x0000000002C9FE48</span><span style="color: #66cc66;">&gt;</span><span style="color: black;">&#93;</span></div></td></tr></tbody></table></div>
<p>Or graphically:<br />
<div id="attachment_77" class="wp-caption aligncenter" style="width: 310px"><a href="http://amitdev.in/blog/wp-content/uploads/2011/08/cyc3.png"><img src="http://amitdev.in/blog/wp-content/uploads/2011/08/cyc3-300x146.png" alt="Cycle 3" title="cyc3" width="300" height="150" class="size-medium wp-image-77" /></a><p class="wp-caption-text">Closure Cycle</p></div></p>
<p>Here, the cycle is more subtle. Since we have a recursive inner function (rare but useful in some cases), there is a <a href="http://docs.python.org/c-api/cell.html">cell</a> object created which holds a reference to the inner function. How to avoid this? Either make Outer a class or explicitly <em>del</em> the reference to inner.</p>
<h2>Conclusion</h3>
<p>Reference cycles can be tricky to notice in python. If your application has disabled gc, then lookout for such cycles using the gc debug options. The <a href="http://mg.pov.lt/objgraph/">objgraph</a> tool is also quite useful in tracking down memory issues (The images shown above where created using it).</p>
]]></content:encoded>
			<wfw:commentRss>http://amitdev.in/blog/?feed=rss2&#038;p=55</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Basics of Concurrent Programming &#8211; 1</title>
		<link>http://amitdev.in/blog/?p=16</link>
		<comments>http://amitdev.in/blog/?p=16#comments</comments>
		<pubDate>Thu, 24 Dec 2009 00:41:00 +0000</pubDate>
		<dc:creator>me</dc:creator>
				<category><![CDATA[concurrency]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[parallelism]]></category>

		<guid isPermaLink="false">http://amitdev.in/blog/?p=16</guid>
		<description><![CDATA[I have some free time and its high time to revive my blog. Since multi-core (r)evolution is expected to make concurrent programming the norm than exception, that is our blog&#8217;s focus area (though I&#8217;ve not completely bought into it). I&#8217;m &#8230; <a href="http://amitdev.in/blog/?p=16">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have some free time and its high time to revive my blog. Since <a href="http://www.gotw.ca/publications/concurrency-ddj.htm">multi-core (r)evolution</a> is expected to make concurrent programming the norm than exception, that is our blog&#8217;s focus area (though I&#8217;ve not completely bought into it). I&#8217;m planning to write a &#8216;for dummies&#8217; series on this topic.</p>
<p>Let&#8217;s start with the basics.</p>
<p>For quite a long period of time, we had concurrency constructs such as <a href="http://en.wikipedia.org/wiki/Semaphore_%28programming%29">Semaphores</a> and <a href="http://en.wikipedia.org/wiki/Monitor_(synchronization)">Monitors</a> (and other less known/used stuff like <a href="http://www.google.co.in/search?q=conditional+critical+section">conditional critical sections</a>, <a href="http://en.wikipedia.org/wiki/Communicating_sequential_processes">CSP </a>etc). Among these, monitors are more popular and provides better abstraction model over semaphores. However semaphores and monitors are like C and Java. One is more flexible/powerful; other one is easier to use. We will leave semaphores for now and start with Monitors.</p>
<p>Time for an example.</p>
<p>Let&#8217;s take the classical Reader/Writer problem.</p>
<blockquote><p>We want to have some shared data where multiple writers are allowed, as well as multiple readers, but at no time should readers and writers be allowed in at the same time. However, multiple readers can read the data at the same time.</p></blockquote>
<p>We will start with a naive java solution (with no concurrency at all). The shared Data can be defined as follows:</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Data <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; StringBuilder value <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StringBuilder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> read<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> value.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> write<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> s<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Writing &quot;</span> <span style="color: #339933;">+</span> s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">value</span>.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span>s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Wrote &quot;</span> <span style="color: #339933;">+</span> s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>It&#8217;s pretty simple. We use <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuilder.html">StringBuilder </a>as the data type, but this can be generalized easily. Our aim is also straightforward &#8211; read and write methods should not execute in parallel. However, multiple reads can happen in parallel.</p>
<p>We also need Readers and Writers to use the data. That is easy too.</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br />30<br />31<br />32<br />33<br />34<br />35<br />36<br />37<br />38<br />39<br />40<br />41<br />42<br />43<br />44<br />45<br />46<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">class</span> <span style="color: #003399;">Reader</span> <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">Thread</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> Data data<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> readerId<span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Reader</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> readerId, Data data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">data</span> <span style="color: #339933;">=</span> data<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">readerId</span> <span style="color: #339933;">=</span> readerId<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; &nbsp; @Override<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> run<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">//Each reader reads 10 times (say)</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Reader &quot;</span><span style="color: #339933;">+</span> readerId <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot; : &quot;</span><span style="color: #339933;">+</span> data.<span style="color: #006633;">read</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #003399;">Writer</span> <span style="color: #000000; font-weight: bold;">extends</span> <span style="color: #003399;">Thread</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> Data data<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> writerId<span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Writer</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> writerId, Data data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">data</span> <span style="color: #339933;">=</span> data<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">writerId</span> <span style="color: #339933;">=</span> writerId<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; &nbsp; @Override<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> run<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">//Each writer writes 10 times (say)</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">10</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data.<span style="color: #006633;">write</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;W&quot;</span> <span style="color: #339933;">+</span> writerId <span style="color: #339933;">+</span> <span style="color: #0000ff;">&quot;:&quot;</span><span style="color: #339933;">+</span> i<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Main <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; Data d <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Data<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">//We have 5 readers and writers as an example.</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> i<span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">5</span><span style="color: #339933;">;</span> <span style="color: #339933;">++</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Reader</span><span style="color: #009900;">&#40;</span>i, d<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Writer</span><span style="color: #009900;">&#40;</span>i, d<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">start</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>If we fire up the Main class, we can see the following output (or something similar):<br />
Writing W0:0<br />
Wrote W0:0<br />
Writing W0:1<br />
Wrote W0:1<br />
Reader 3 : W0:0W0:1<br />
Reader 3 : W0:0W0:1<br />
&#8230;</p>
<p>As you can guess this solution does not work as read and write can be called simultaneously. So you may see output like:<br />
Writing W0:0<br />
Reader 3 :<br />
Wrote W0:0</p>
<p>That is, some one is reading while you are writing. There are many other <a href="http://en.wikipedia.org/wiki/Race_conditions">race conditions</a> that can happen like two writers writing simultaneously etc.</p>
<p>Ok, let&#8217;s make our Data class ready for concurrent access. A naive way of doing that would be to make read and write methods synchronized. But that would block multiple readers accessing the data too, which is restrictive. We will be effectively serializing the access to Data.<br />
Digression: Java initially had <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/Hashtable.html">Hashtable </a>and Vector classes which suffered from this problem. All the methods were synchronized, so if someone was checking the length of the collection, he will block others who are doing get (or any other read operation). This problem was finally solved from Java 1.5 onwards with concurrent collections.</p>
<p>Back to Reader/Writer. We need to track who is accessing the data and synchronize accordingly. So we maintain no.of readers currently reading. Writers wait if someone is reading. The last reader and writer notifies any waiting writer. Readers can go in simultaneously. Our modified Data class will look like:</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Data <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> StringBuilder value <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StringBuilder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">int</span> readers <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> read<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; readers<span style="color: #339933;">++;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">String</span> val <span style="color: #339933;">=</span> value.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; readers<span style="color: #339933;">--;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>readers <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> notify<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> val<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">synchronized</span> <span style="color: #000066; font-weight: bold;">void</span> write<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> s<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>readers <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wait<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">InterruptedException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Writing &quot;</span> <span style="color: #339933;">+</span> s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">value</span>.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span>s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Wrote &quot;</span> <span style="color: #339933;">+</span> s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; notify<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>Reader and writer remains the same. However, this is already getting complicated. Java has <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/locks/ReadWriteLock.html">ReadWriteLock </a>from 1.5 onwards, so you can use it directly instead of reinventing it. With that our solution will look like:</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.concurrent.locks.ReadWriteLock</span><span style="color: #339933;">;</span><br />
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.concurrent.locks.ReentrantReadWriteLock</span><span style="color: #339933;">;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Data <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> StringBuilder value <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> StringBuilder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> ReadWriteLock lock <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ReentrantReadWriteLock<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> read<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lock.<span style="color: #006633;">readLock</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">lock</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> value.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lock.<span style="color: #006633;">readLock</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">unlock</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> write<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> s<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lock.<span style="color: #006633;">writeLock</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">lock</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Writing &quot;</span> <span style="color: #339933;">+</span> s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">value</span>.<span style="color: #006633;">append</span><span style="color: #009900;">&#40;</span>s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Wrote &quot;</span> <span style="color: #339933;">+</span> s<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lock.<span style="color: #006633;">writeLock</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">unlock</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>This is much simpler. In the background it will be doing stuff similar to what we did above. The advantage is we don&#8217;t have to maintain the queue and logic is much simpler. However, there is limited control on the fairness. In the above example, we had specified the ReadWriteLock to be fair, which means the system will provide a weak FIFO semantics for waiting threads. Other option is no fairness at all. But if we keep track of readers our-self (like in previous implementation) we can provide arbitrary priorities like Reader have more priority over writers and vice verse.</p>
<p>Anyway, that&#8217;s all for the first installment. Let me know your comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://amitdev.in/blog/?feed=rss2&#038;p=16</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>N Queens in Scala</title>
		<link>http://amitdev.in/blog/?p=15</link>
		<comments>http://amitdev.in/blog/?p=15#comments</comments>
		<pubDate>Wed, 08 Jul 2009 03:20:00 +0000</pubDate>
		<dc:creator>me</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://amitdev.in/blog/?p=15</guid>
		<description><![CDATA[Its been a while since I blogged. Even this is not a blog entry, its just a scala code snippet to solve the N queen problem. Its not particularly efficient, but by using lazy lists, we can run it on &#8230; <a href="http://amitdev.in/blog/?p=15">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I blogged. Even this is not a blog entry, its just a scala code snippet to solve the N queen problem. Its not particularly efficient, but by using lazy lists, we can run it on large numbers and get the first few results. Right now, not so lazy version:</p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">object</span> q <span style="color: #0000ff; font-weight: bold;">extends</span> Application <span style="color: #F78811;">&#123;</span><br />
<br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">def</span> check<span style="color: #F78811;">&#40;</span>a<span style="color: #000080;">:</span> Tuple2<span style="color: #F78811;">&#91;</span>Int, Int<span style="color: #F78811;">&#93;</span>, b<span style="color: #000080;">:</span> Tuple2<span style="color: #F78811;">&#91;</span>Int, Int<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span><br />
&nbsp; &nbsp; a.<span style="color: #000080;">_</span>1 <span style="color: #000080;">==</span> b.<span style="color: #000080;">_</span>2 || <span style="color: #F78811;">&#40;</span>a.<span style="color: #000080;">_</span>1+a.<span style="color: #000080;">_</span>2 <span style="color: #000080;">==</span> b.<span style="color: #000080;">_</span>1+b.<span style="color: #000080;">_</span>2<span style="color: #F78811;">&#41;</span> || <span style="color: #F78811;">&#40;</span>a.<span style="color: #000080;">_</span>2-a.<span style="color: #000080;">_</span>1 <span style="color: #000080;">==</span> b.<span style="color: #000080;">_</span>1-b.<span style="color: #000080;">_</span>2<span style="color: #F78811;">&#41;</span><br />
<br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">def</span> safe<span style="color: #F78811;">&#40;</span>p<span style="color: #000080;">:</span> List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span>, n<span style="color: #000080;">:</span> Int<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> p.<span style="color: #000000;">zipWithIndex</span>.<span style="color: #000000;">forall</span><span style="color: #F78811;">&#40;</span><span style="color: #000080;">!</span>check<span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>, <span style="color: #F78811;">&#40;</span>p.<span style="color: #000000;">size</span>, n<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><br />
<br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">def</span> queens<span style="color: #F78811;">&#40;</span>m<span style="color: #000080;">:</span> Int<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span>n<span style="color: #000080;">:</span> Int<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> List<span style="color: #F78811;">&#91;</span>List<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span><br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>m <span style="color: #000080;">==</span> <span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; List<span style="color: #F78811;">&#40;</span>Nil<span style="color: #F78811;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">else</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>p <span style="color: #000080;">&lt;</span>- queens<span style="color: #F78811;">&#40;</span>m-<span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span>n<span style="color: #F78811;">&#41;</span><span style="color: #000080;">;</span> i <span style="color: #000080;">&lt;</span>- <span style="color: #F78811;">&#40;</span><span style="color: #F78811;">0</span> until n<span style="color: #F78811;">&#41;</span><span style="color: #000080;">;</span> <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>safe<span style="color: #F78811;">&#40;</span>p, i<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">yield</span> p <span style="color: #000080;">:::</span> List<span style="color: #F78811;">&#40;</span>i<span style="color: #F78811;">&#41;</span><br />
<br />
&nbsp; println<span style="color: #F78811;">&#40;</span>queens<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">8</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">8</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <br />
<span style="color: #F78811;">&#125;</span></div></td></tr></tbody></table></div>
]]></content:encoded>
			<wfw:commentRss>http://amitdev.in/blog/?feed=rss2&#038;p=15</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler with Scala</title>
		<link>http://amitdev.in/blog/?p=14</link>
		<comments>http://amitdev.in/blog/?p=14#comments</comments>
		<pubDate>Tue, 22 Jul 2008 04:21:00 +0000</pubDate>
		<dc:creator>me</dc:creator>
				<category><![CDATA[Functional]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://amitdev.in/blog/?p=14</guid>
		<description><![CDATA[I came across this interesting post about solving some Project Euler questions using Scala. Being a fan of Project Euler myself, I though I&#8217;ll outline some of the solutions that I came up using Scala. Of course, I have taken &#8230; <a href="http://amitdev.in/blog/?p=14">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I came across <a href="http://scala-blogs.org/2007/12/project-euler-fun-in-scala.html">this</a> interesting post about solving some <a href="http://projecteuler.net/">Project Euler</a> questions using Scala. Being a fan of Project Euler myself, I though I&#8217;ll outline some of the solutions that I came up using Scala. Of course, I have taken trivial examples and the objective is more to learn Scala than to have an efficient solution. So here are some examples:<br />
<span style="color: #ff6666;">Warning: Spoilers ahead.</span></p>
<p><span style="font-weight: bold;">Problem <a href="http://projecteuler.net/index.php?section=problems&amp;id=13">13</a>.</span><br />
&#8220;Work out the first ten digits of the sum of the following one-hundred 50-digit numbers&#8221;. And hundred 50-digit numbers are given. (Not listing the numbers here to avoid clutter).</p>
<p>One possible solution:</p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">object</span> P13 <span style="color: #0000ff; font-weight: bold;">extends</span> Application <span style="color: #F78811;">&#123;</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">val</span> s <span style="color: #000080;">=</span> <span style="color: #6666FF;">&quot;...&quot;</span> <span style="color: #008000; font-style: italic;">//The numbers as a string separated by space.</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">val</span> numbers <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>number <span style="color: #0000ff; font-weight: bold;">val</span> zero<span style="color: #000080;">:</span>BigInt <span style="color: #000080;">=</span> <span style="color: #F78811;">0</span><br />
&nbsp; println <span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#40;</span>zero /<span style="color: #000080;">:</span> numbers<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>+<span style="color: #000080;">_</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">toString</span>.<span style="color: #000000;">substring</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">0</span>, <span style="color: #F78811;">10</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><br />
<span style="color: #F78811;">&#125;</span></div></td></tr></tbody></table></div>
<p>Hmm, pretty simple program. We define an object which extends <a href="http://www.scala-lang.org/docu/files/api/scala/Application.html">Application</a>, so that we don&#8217;t have to write main method. Then we initialize the variable. Next line simply parses the string and creates a List of BigInts. We have a constant &#8216;zero&#8217; which is BigInt 0. Finally we add the numbers using fold and take first 10 characters. If you don&#8217;t like /:, you can also use (numbers.foldLeft(zero)(_+_).</p>
<p><span style="font-weight: bold;">Problem <a href="http://projecteuler.net/index.php?section=problems&amp;id=22">22</a>.</span></p>
<p>&#8220;Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.&#8221;<br />
One possible solution:</p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">import</span> java.<span style="color: #000000;">io</span>.<span style="color: #000080;">_</span><br />
<span style="color: #0000ff; font-weight: bold;">import</span> scala.<span style="color: #000000;">collection</span>.<span style="color: #000000;">jcl</span>.<span style="color: #000080;">_</span><br />
<span style="color: #0000ff; font-weight: bold;">object</span> P22 <span style="color: #0000ff; font-weight: bold;">extends</span> Application <span style="color: #F78811;">&#123;</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">val</span> res <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> BufferedReader<span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">new</span> FileReader<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;c:<span style="color: #0000ff; font-weight: bold;">\\</span>names.txt&quot;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">readLine</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">val</span> actualNames <span style="color: #000080;">=</span> res.<span style="color: #000000;">split</span><span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;,&quot;</span><span style="color: #F78811;">&#41;</span> map <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">filter</span><span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">isLetter</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">mkString</span><span style="color: #F78811;">&#41;</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">val</span> sorted <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> TreeSet<span style="color: #F78811;">&#91;</span>String<span style="color: #F78811;">&#93;</span><br />
&nbsp; sorted ++<span style="color: #000080;">=</span> actualNames<br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">val</span> nums <span style="color: #000080;">=</span> sorted map <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">foldLeft</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>+<span style="color: #000080;">_</span>-<span style="color: #F78811;">64</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">var</span> sum<span style="color: #000080;">:</span> BigInt <span style="color: #000080;">=</span> <span style="color: #F78811;">0</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">var</span> t <span style="color: #000080;">=</span> <span style="color: #F78811;">0</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>j t +<span style="color: #000080;">=</span> <span style="color: #F78811;">1</span><br />
&nbsp; &nbsp; sum +<span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span>t <span style="color: #000080;">*</span> j<span style="color: #F78811;">&#41;</span><br />
&nbsp; <span style="color: #F78811;">&#125;</span><br />
&nbsp; println<span style="color: #F78811;">&#40;</span>sum<span style="color: #F78811;">&#41;</span><br />
<span style="color: #F78811;">&#125;</span></div></td></tr></tbody></table></div>
<p>First, we read the lines of the file (so easy with scala). Then split based on &#8216;,&#8217; and strip off the &#8216;&#8221;&#8216;. Create a sorted set (we are using the same TreeSet from Java) and add the names. Calculate the value using fold left (Since they are upcase chars, subtract 64 to get int values). Ok, now we need to multiply each number by its position. Easy thing to do in imperative fashion. So lets do a traditional for each loop and that&#8217;s it.</p>
<p><span style="color: #33cc00;">Update:</span> Seth Tisue pointed out that zipWithIndex can be used to do the final calculation. The problem considers index starting with 1, so we cannot directly use zipWithIndex. However zip can be used as below:</p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">val</span> l <span style="color: #000080;">=</span> nums toList<br />
<span style="color: #0000ff; font-weight: bold;">val</span> indices <span style="color: #000080;">=</span> <span style="color: #F78811;">1</span> to l.<span style="color: #000000;">size</span> toList<br />
l.<span style="color: #000000;">zip</span><span style="color: #F78811;">&#40;</span>indices<span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">foldLeft</span><span style="color: #F78811;">&#40;</span>sum<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#40;</span>a,b<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> a + b.<span style="color: #000080;">_</span>1 <span style="color: #000080;">*</span> b.<span style="color: #000080;">_</span>2<span style="color: #F78811;">&#41;</span></div></td></tr></tbody></table></div>
<p><span style="font-weight: bold;">Problem <a href="http://projecteuler.net/index.php?section=problems&amp;id=42">42</a></span></p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">import</span> java.<span style="color: #000000;">io</span>.<span style="color: #000080;">_</span><br />
<span style="color: #0000ff; font-weight: bold;">import</span> scala.<span style="color: #000000;">collection</span>.<span style="color: #000000;">jcl</span>.<span style="color: #000080;">_</span><br />
<span style="color: #0000ff; font-weight: bold;">object</span> P42 <span style="color: #0000ff; font-weight: bold;">extends</span> Application <span style="color: #F78811;">&#123;</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">val</span> triangular <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> TreeSet<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>i <span style="color: #0000ff; font-weight: bold;">val</span> lines <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> BufferedReader<span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">new</span> FileReader<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;c:<span style="color: #0000ff; font-weight: bold;">\\</span>words.txt&quot;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">readLine</span><br />
&nbsp; <span style="color: #0000ff; font-weight: bold;">val</span> nums <span style="color: #000080;">=</span> lines.<span style="color: #000000;">split</span><span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;,&quot;</span><span style="color: #F78811;">&#41;</span> map <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">filter</span><span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">isLetter</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">mkString</span><span style="color: #F78811;">&#41;</span> map <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">foldLeft</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>+<span style="color: #000080;">_</span>-<span style="color: #F78811;">64</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><br />
&nbsp; println<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">0</span> /<span style="color: #000080;">:</span> nums<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#40;</span> <span style="color: #F78811;">&#40;</span>result, num<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> <br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>triangular contains num<span style="color: #F78811;">&#41;</span> result+<span style="color: #F78811;">1</span> <span style="color: #0000ff; font-weight: bold;">else</span> result <span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><br />
<span style="color: #F78811;">&#125;</span></div></td></tr></tbody></table></div>
<p>By now this should be obvious. This example is similar to the one above. First we cache first 40 triangular numbers in an Array. Then read the file. Split lines by &#8216;,&#8217;, ignore special characters (by filtering) and find the required sum (using map). I&#8217;ve done it in one line as it appears natural. Finally, count the triangular numbers. I used a fold, but it can be done imperatively as well.</p>
<p>Hope you enjoyed it. Do let me know if you think there are better ways of doing this (Not in terms of <span style="font-style: italic;">performance</span>, but in terms of <span style="font-style: italic;">elegance </span>or <span style="font-style: italic;">functional style</span>).</p>
]]></content:encoded>
			<wfw:commentRss>http://amitdev.in/blog/?feed=rss2&#038;p=14</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Design Patterns in Scala</title>
		<link>http://amitdev.in/blog/?p=13</link>
		<comments>http://amitdev.in/blog/?p=13#comments</comments>
		<pubDate>Sun, 30 Mar 2008 00:40:00 +0000</pubDate>
		<dc:creator>me</dc:creator>
				<category><![CDATA[Design]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://amitdev.in/blog/?p=13</guid>
		<description><![CDATA[Design patterns in Scala The GoF Design Patterns are perhaps the most popular design fads of Software ever. However some people argue that they are more or less solutions to the deficiencies of Language itself (particularly C++/Java) and if the &#8230; <a href="http://amitdev.in/blog/?p=13">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Design patterns in Scala</p>
<p>The GoF Design Patterns are perhaps the most popular design fads of Software ever. However some people argue that they are more or less solutions to the deficiencies of Language itself (particularly C++/Java) and if the language is powerful enough they are redundant. Consider this excellent <a href="http://norvig.com/design-patterns/">presentation</a> from Peter Norvig for example.<br />
I agree that patterns translate to quite natural and concise code in some languages, but the <span style="font-style: italic;">intend</span> of the pattern may still be important. So lets consider some of the popular patterns in Scala &#8211; a language which like Ruby/Lisp etc reduces Pattern <span style="font-style: italic;">implementation </span>to triviality (though its not a dynamic language!).</p>
<p><span style="font-weight: bold;">1. Singleton</span><br />
Singleton is one of the frequently (over)used patterns. In spite of being the simplest of patterns, it is surprisingly difficult to implement a &#8216;pure&#8217; singleton in Java. The particularly famous <a href="http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html">Double-checked locking</a> and <a href="http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html">so on</a>. However, in Scala it is trivial. Lets say you need to create a Registry object which is singleton. You can do that in the following way:</p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">object</span> Registry <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">def</span> getEntry<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> Entry <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #F78811;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #008000; font-style: italic;">//Other fields/methods</span><br />
<span style="color: #F78811;">&#125;</span><br />
<span style="color: #008000; font-style: italic;">//Create and use the singleton</span><br />
<span style="color: #0000ff; font-weight: bold;">val</span> entry <span style="color: #000080;">=</span> Registry.<span style="color: #000000;">getEntry</span></div></td></tr></tbody></table></div>
<p>Thats it! The only difference from defining a normal class is that instead of the &#8216;class&#8217; keyword we used &#8216;object&#8217;. If you have to map it back to java, this is equivalent of defining a class and all its fields/methods are static.</p>
<p><span style="font-weight: bold;">2. Strategy</span><br />
Like any language where functions are first-class objects or where closures are available, Strategy pattern is obvious. For eg. consider the &#8216;taxing&#8217; example:</p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">trait</span> TaxPayer<br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #0000ff; font-weight: bold;">class</span> Employee<span style="color: #F78811;">&#40;</span>sal<span style="color: #000080;">:</span> Long<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">extends</span> TaxPayer<br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #0000ff; font-weight: bold;">class</span> NonProfitOrg<span style="color: #F78811;">&#40;</span>funds<span style="color: #000080;">:</span> BigInt<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">extends</span> TaxPayer<br />
<br />
<span style="color: #008000; font-style: italic;">//Consider a generic tax calculation function. (It can be in TaxPayer also).</span><br />
<span style="color: #0000ff; font-weight: bold;">def</span> calculateTax<span style="color: #F78811;">&#40;</span>t<span style="color: #000080;">:</span> TaxPayer, strategy<span style="color: #000080;">:</span> <span style="color: #F78811;">&#40;</span>TaxPayer <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">double</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; strategy<span style="color: #F78811;">&#40;</span>victim<span style="color: #F78811;">&#41;</span><br />
<span style="color: #F78811;">&#125;</span><br />
<br />
<span style="color: #0000ff; font-weight: bold;">val</span> employee <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> Employee<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1000</span><span style="color: #F78811;">&#41;</span><br />
<span style="color: #008000; font-style: italic;">//A strategy to calculate tax for employees</span><br />
<span style="color: #0000ff; font-weight: bold;">def</span> empStrategy<span style="color: #F78811;">&#40;</span>e<span style="color: #000080;">:</span> Employee<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> Math.<span style="color: #000000;">ceil</span><span style="color: #F78811;">&#40;</span>e.<span style="color: #000000;">sal</span> <span style="color: #000080;">*</span> .3<span style="color: #F78811;">&#41;</span> toLong<br />
calculateTax<span style="color: #F78811;">&#40;</span>employee, empStrategy<span style="color: #F78811;">&#41;</span><br />
<br />
<span style="color: #0000ff; font-weight: bold;">val</span> npo <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> NonProfitOrg<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">100000000</span><span style="color: #F78811;">&#41;</span><br />
<span style="color: #008000; font-style: italic;">//The tax calculation strategy for npo is trivial, so we can inline it</span><br />
calculateTax<span style="color: #F78811;">&#40;</span>nonProfit, <span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#40;</span>t<span style="color: #000080;">:</span> TaxPayer<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> <span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span></div></td></tr></tbody></table></div>
<p><span style="font-weight: bold;">3. Factory</span><br />
Factory pattern addresses the fact that object constructors cannot return arbitrary objects. If you call constructor of object A, you always get an object A. If you need different objects based on parameter types, you typically create a Singleton Factory. In Scala also you need to do the same thing, but in a bit more elegant manner.</p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">object</span> Car <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">def</span> apply<span style="color: #F78811;">&#40;</span>String <span style="color: #0000ff; font-weight: bold;">type</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">type</span> <span style="color: #0000ff; font-weight: bold;">match</span> <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #6666FF;">&quot;Race&quot;</span> &nbsp; <span style="color: #000080;">=&gt;</span> <span style="color: #0000ff; font-weight: bold;">new</span> RaceCar<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #6666FF;">&quot;Normal&quot;</span> <span style="color: #000080;">=&gt;</span> <span style="color: #0000ff; font-weight: bold;">new</span> NormalCar<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #000080;">_</span> &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000080;">=&gt;</span> <span style="color: #0000ff; font-weight: bold;">throw</span> <span style="color: #0000ff; font-weight: bold;">new</span> Exception<span style="color: #000080;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #F78811;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #F78811;">&#125;</span><br />
<span style="color: #F78811;">&#125;</span><br />
<span style="color: #008000; font-style: italic;">//And you can create cars like:</span><br />
<span style="color: #0000ff; font-weight: bold;">val</span> myCar <span style="color: #000080;">=</span> Car<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;Race&quot;</span><span style="color: #F78811;">&#41;</span><br />
<span style="color: #008000; font-style: italic;">//instead of more verbose</span><br />
<span style="color: #008000; font-style: italic;">//Car myCar = CarFactory.getInstance().createCar(&quot;Ferrari&quot;);</span></div></td></tr></tbody></table></div>
<p>Basically, you can exploit the fact that what apparently looks like a constructor call to a singleton object is syntactic sugar for the &#8220;apply&#8221; method.<br />
<span style="font-weight: bold;">4. Visitor</span><br />
Visitor pattern is considered harmful by <a href="http://www.google.com/search?q=visitor+pattern+harmful">many</a> people, but still it has its value at specific cases. Lets see a typical java implementation of Visitor pattern:</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> Expression <span style="color: #009900;">&#123;</span><br />
<span style="color: #666666; font-style: italic;">//...</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> accept<span style="color: #009900;">&#40;</span>Visitor v<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">class</span> Identifier <span style="color: #000000; font-weight: bold;">extends</span> Expression <span style="color: #009900;">&#123;</span><br />
<span style="color: #009900;">&#125;</span><br />
<span style="color: #000000; font-weight: bold;">class</span> Sum <span style="color: #000000; font-weight: bold;">extends</span> Expression <span style="color: #009900;">&#123;</span><br />
<span style="color: #009900;">&#125;</span><br />
<span style="color: #666666; font-style: italic;">//..</span><br />
<br />
<span style="color: #000000; font-weight: bold;">class</span> Visitor <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> visit<span style="color: #009900;">&#40;</span>Identifier i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> visit<span style="color: #009900;">&#40;</span>Sum s<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>Typical java boilerplate code as you would expect. In Scala you can achieve the same result by using pattern matching:</p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">trait</span> Expression <span style="color: #F78811;">&#123;</span><br />
<span style="color: #008000; font-style: italic;">//...</span><br />
<span style="color: #F78811;">&#125;</span><br />
<span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #0000ff; font-weight: bold;">class</span> Identifier<span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span> Int<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">extends</span> Expression <span style="color: #F78811;">&#123;</span><br />
<span style="color: #F78811;">&#125;</span><br />
<span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #0000ff; font-weight: bold;">class</span> Sum <span style="color: #0000ff; font-weight: bold;">extends</span> Expression <span style="color: #F78811;">&#123;</span><br />
<span style="color: #F78811;">&#125;</span><br />
<br />
<span style="color: #0000ff; font-weight: bold;">object</span> EvalVisitor <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">def</span> visit<span style="color: #F78811;">&#40;</span>expr<span style="color: #000080;">:</span> Expression<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> Int <span style="color: #000080;">=</span> expr <span style="color: #0000ff; font-weight: bold;">match</span> <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #F78811;">&#40;</span>Identifier<span style="color: #F78811;">&#40;</span>v<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> v<br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #F78811;">&#40;</span>Sum<span style="color: #F78811;">&#40;</span>e1, e2<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span> &nbsp; <span style="color: #000080;">=&gt;</span> visit<span style="color: #F78811;">&#40;</span>e1<span style="color: #F78811;">&#41;</span> + visit<span style="color: #F78811;">&#40;</span>e2<span style="color: #F78811;">&#41;</span><br />
&nbsp; &nbsp; <span style="color: #F78811;">&#125;</span><br />
<span style="color: #F78811;">&#125;</span></div></td></tr></tbody></table></div>
<p>The pattern matching code is also more flexible.<br />
<span style="font-weight: bold;">5. Decorator</span><br />
Finally consider the Decorator pattern. Since Scala supports mixins and implicit conversions, Decorator is also simple and natural. Conceptually, there are two ways you can decorate an object &#8211; by adding new functionality and extending existing functionality.<br />
To decorate a class with new functionality, you can use implicit conversions. Consider the RichInt class in scala standard library in action:</p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">val</span> range1to10 <span style="color: #000080;">=</span> <span style="color: #F78811;">1</span> to <span style="color: #F78811;">10</span></div></td></tr></tbody></table></div>
<p>which in scala translates to 1.to(10). However, there is no method &#8220;to&#8221; in Int class. So how does it work? Scala has an innovative concept called Implicits for <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=179766">pimping your library</a>. In essence it is Ruby&#8217;s open classes but lexically scoped. Its interesting stuff and you can read about it <a href="http://unenterprise.blogspot.com/2008/03/introduction-to-implicit-arguments.html">elsewhere</a>. For us, it suffices to say that there is an implicit conversion in Predef [implicit def intWrapper(x : Int) : RichInt] that does the trick.<br />
Mixins are also good for decorating your classes and extend its functionality in different dimensions. For example consider the typical Reader interface:</p>
<div class="codecolorer-container scala default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br /></div></td><td><div class="scala codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #0000ff; font-weight: bold;">trait</span> Reader <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">type</span> T<br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">def</span> read<span style="color: #000080;">:</span> T<br />
<span style="color: #F78811;">&#125;</span><br />
<span style="color: #0000ff; font-weight: bold;">trait</span> SynchronizedReader <span style="color: #0000ff; font-weight: bold;">extends</span> Reader <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">abstract</span> <span style="color: #0000ff; font-weight: bold;">override</span> <span style="color: #0000ff; font-weight: bold;">def</span> read<span style="color: #000080;">:</span> T <span style="color: #000080;">=</span> synchronized<span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">super</span>.<span style="color: #000000;">next</span><span style="color: #F78811;">&#41;</span><br />
<span style="color: #F78811;">&#125;</span><br />
<br />
<span style="color: #0000ff; font-weight: bold;">trait</span> BufferedReader <span style="color: #0000ff; font-weight: bold;">extends</span> Reader <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">abstract</span> <span style="color: #0000ff; font-weight: bold;">override</span> <span style="color: #0000ff; font-weight: bold;">def</span> read<span style="color: #000080;">:</span> T <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #008000; font-style: italic;">//buffering code</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">super</span>.<span style="color: #000000;">read</span><br />
&nbsp; &nbsp; <span style="color: #F78811;">&#125;</span><br />
<span style="color: #F78811;">&#125;</span><br />
<br />
<span style="color: #008000; font-style: italic;">//A concrete implementation</span><br />
<span style="color: #0000ff; font-weight: bold;">class</span> FileReader <span style="color: #0000ff; font-weight: bold;">extends</span> Reader <span style="color: #F78811;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">type</span> T <span style="color: #000080;">=</span> <span style="color: #9999cc; font-weight: bold;">char</span><br />
&nbsp; &nbsp; <span style="color: #0000ff; font-weight: bold;">def</span> read<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">char</span> <span style="color: #000080;">=</span> readSomehow<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span><br />
<span style="color: #F78811;">&#125;</span><br />
<br />
<span style="color: #008000; font-style: italic;">//Now we can mix in stuff that we need</span><br />
<span style="color: #008000; font-style: italic;">//Create a FileReader</span><br />
<span style="color: #0000ff; font-weight: bold;">val</span> f <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> FileReader<br />
<span style="color: #008000; font-style: italic;">//create a fileReader which is synchronized</span><br />
<span style="color: #0000ff; font-weight: bold;">val</span> syncReader <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> FileReader <span style="color: #0000ff; font-weight: bold;">with</span> SynchronizedReader<br />
<span style="color: #008000; font-style: italic;">//create a fileReader which is synchronized and buffered</span><br />
<span style="color: #0000ff; font-weight: bold;">val</span> bsReader <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> FileReader <span style="color: #0000ff; font-weight: bold;">with</span> BufferedReader <span style="color: #0000ff; font-weight: bold;">with</span> SynchronizedReader</div></td></tr></tbody></table></div>
<p><span style="font-weight: bold;">Conclusion</span><br />
Design Patterns are good recipes for designing software. However, most of them generally solve a language issue than a design issue. If you have a good Language patterns (at least most of them) will become trivial. For example, in a structured language, the concepts of virtual methods or classes may be a &#8216;Design Pattern&#8217;. Once you move to a powerful language, the design patterns that you deal with will also change. They will be at a higher level of abstraction. More on it later!</p>
]]></content:encoded>
			<wfw:commentRss>http://amitdev.in/blog/?feed=rss2&#038;p=13</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>To Ruby or To Scala?</title>
		<link>http://amitdev.in/blog/?p=12</link>
		<comments>http://amitdev.in/blog/?p=12#comments</comments>
		<pubDate>Mon, 18 Feb 2008 04:47:00 +0000</pubDate>
		<dc:creator>me</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://amitdev.in/blog/?p=12</guid>
		<description><![CDATA[I have been exploring alternate languages for JVM for some time now. Why? Certainly not because I think the Java language is dying. Though java is devolving, it has crossed the threshold of immortality &#8211; there are way too many &#8230; <a href="http://amitdev.in/blog/?p=12">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have been exploring alternate languages for JVM for some time now.<br />
Why? Certainly not because I think the Java language is <a href="http://gafter.blogspot.com/2008/01/is-java-dying.html">dying</a>. Though java is devolving, it has crossed the threshold of immortality &#8211; there are way too many applications written in java and java developers can be busy just by maintaining them (and also by inventing &#8216;frameworks&#8217; to get around the deficiency of the language like DI, AOP etc). However, I have started to realize the <span style="font-style: italic;">power</span> of languages &#8211; maybe even to the extend of believing the <a href="http://en.wikipedia.org/wiki/Sapir%E2%80%93Whorf_hypothesis">Sapir–Whorf hypothesis</a>. And finally, I still believe that the JVM is one of the best deployment platforms available today and java has lots of ready to use libraries &#8211; so I don&#8217;t want to miss them as well. Luckily, there are host of new languages targeted at the JVM &#8211; Jython, JRuby, Groovy, Scala, Rhino, Clojure etc.</p>
<p>Finally I&#8217;ve narrowed down to two: JRuby and Scala. I&#8217;ll try to outline the positives and negatives of both.</p>
<p>Ruby is an extremely dynamic language. It is dynamically (and strongly) typed. In my opinion, Ruby is the best language for internal DSLs (maybe next only to Lisp). Most of the successful Ruby projects have some kind of DSLs &#8211; like Rails, Rake, Builders etc. In a way, DSLs are nothing but flexible and easy-to-use interfaces.<br />
Scala is a statically (and strongly) typed language. However, it has a powerful type inference system to avoid the pain of providing the types. It looks suitable for large systems, where precisely defined interfaces are required.</p>
<p>So looks to me that these languages have their own niche in programming. If you need RAD, clean, flexible and easy-to-use interfaces and small to medium sized applications, use Ruby. For large scale applications, where type safety is more important, use Scala without the burden of statically typed language.</p>
<p>Lets see how these fair in the <a href="http://memuser.blogspot.com/2008/01/what-make-programming-language-popular.html">popularity</a> factor:</p>
<ol>
<li>Popularity: Ruby is already a popular language (thanks mainly to Rails), while Scala is not (yet).</li>
<li>Ease-of-learning: Scala is probably a bit easier for Java folks. But in terms of documentation Ruby clearly excels. Scala documentation is poor, though it is improving.</li>
<li>Ease-of-writing: Ruby maybe an inch ahead as it is dynamically typed.</li>
<li>Ease-of-reading: For large systems, Scala seems to be a winner (thanks to static typing).</li>
<li>Terse: Both languages support functional/OO/imperative style, and not much difference here as well.</li>
</ol>
<p>I would also outline some cool features of these languages:<br />
Mixins: Both of these languages support mixins (though in Scala it is in a controlled way)<br />
Open classes: Basically you can add methods to existing classes any time you wish. Scala also supports this through <span style="font-style: italic;">implicits</span>.<br />
Functional programming: Both languages has true closures, you can use functions as values etc.<br />
Again, in Ruby you have complete freedom, while in Scala it is more controlled.</p>
<p>Of course, as a last point, the tool support is no way near to that in Java. The IDE support (in terms of auto completion, debugging, profiling etc) is currently mediocre in these languages. Also the performance is not that great. It could only be a matter of time, though. And btw, we needed those IDEs because Java was too bad anyway <img src='http://amitdev.in/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>To conclude, there is no <a href="http://info.computer.org/portal/site/computer/menuitem.eb7d70008ce52e4b0ef1bd108bcd45f3/index.jsp?&amp;pName=computer_level1&amp;path=computer/homepage/misc/Brooks&amp;file=index.xml&amp;xsl=article.xsl">silver bullet</a> in programming languages. I guess we are moving towards polyglot programming where synergy of multiple languages will greatly help in tackling complexity.</p>
]]></content:encoded>
			<wfw:commentRss>http://amitdev.in/blog/?feed=rss2&#038;p=12</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>What&#8217;s a Software Engineer?</title>
		<link>http://amitdev.in/blog/?p=11</link>
		<comments>http://amitdev.in/blog/?p=11#comments</comments>
		<pubDate>Mon, 28 Jan 2008 05:13:00 +0000</pubDate>
		<dc:creator>me</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://amitdev.in/blog/?p=11</guid>
		<description><![CDATA[Recently there has been some debates on the definition of &#8216;Engineer&#8217; and what Software Engineers do is not strictly engineering etc. Looks like Reg Brathwaite started it and Ravi Mohan wrote an excellent follow through. Of course not all agree &#8230; <a href="http://amitdev.in/blog/?p=11">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Recently there has been some debates on the definition of &#8216;Engineer&#8217; and what Software Engineers do is not strictly engineering etc. Looks like Reg Brathwaite <a href="http://weblog.raganwald.com/2008/01/no-disrespect.html">started it</a> and Ravi Mohan wrote an <a href="http://ravimohan.blogspot.com/2008/01/ratcatchers-and-engineers.html">excellent</a> follow through. Of course not all agree with this. I&#8217;ll propound my definition of what we (Software Engineers) do:<br />
Definitely our work (or atleast for the majority) does not resemble &#8216;Engineering&#8217;. To put things into perspective here&#8217;s one definition taken from <a href="http://en.wikipedia.org/wiki/Engineering">Wikipedia</a>:</p>
<blockquote><p>&#8220;The creative application of scientific principles to design or develop structures, machines, apparatus, or manufacturing processes, or works utilizing them singly or in combination; or to construct or operate the same with full cognizance of their design; or to forecast their behavior under specific operating conditions; all as respects an intended function, economics of operation and safety to life and property.&#8221;</p></blockquote>
<p>[Well, in my opinion that just shows how difficult it is to define a term like 'Engineering'.]</p>
<p>Anyway, applying that to Software, one can readily reflect that &#8216;Engineering&#8217; is a misnomer. But then what&#8217;s a more appropriate term for it? Before coming up with a new term, let&#8217;s see what really makes it different from other engineering disciplines:</p>
<p><span style="font-weight: bold;">1. It is impossible to define software.</span><br />
In most of the Engineering fields, the end product is often cleanly and precisely defined. Consider the building that you are sitting. First, it has definite attributes which can be defined beforehand. Like no.of floors, total area etc.<br />
Now consider any piece of software that you have developed. Unless it was a small piece of code<sup><a name="backfoot1"></a><a href="http://memuser.blogspot.com/2008/01/whats-software-engineer.html#footnote1">1</a></sup>, chances are that its definition itself changed over time. Even if it didn&#8217;t, you have something which you can&#8217;t define completely.</p>
<p><span style="font-weight: bold;">2. Software is inherently complex.</span><br />
This is so well known that I won&#8217;t dwell into it. The take-away is that building software is generally more complex than building a building (no pun intended). I agree with Harold Abelson that Computer Science is all about managing complexity.</p>
<p><span style="font-weight: bold;">3. Software development need not require &#8216;theoretical backing&#8217;</span><br />
This is the key point which generates lot of heat. In fact this is the answer (or atleast one of the answers) to questions like why is Lisp/FP not popular or why is java popular. Unlike other disciplines of Engineering, software development does not require any Mathematical knowledge. And there has been a plethora of software developers who entered this field just because of this fact and have greatly contributed to the complexity of already complex software development. Needless to say, the minority of software developers who <span style="font-style: italic;">does</span> know theory and develops software that is <a href="http://www-formal.stanford.edu/jmc/recursive/recursive.html">inexpressibly beautiful</a> or that is <a href="http://www.dreamsongs.com/ArtOfLisp.html">indistinguishable from art</a> also are dwarfed to the category of &#8216;Software Engineers&#8217;.</p>
<p>I hope that by now it is clear that &#8216;Engineering&#8217; is not the right term. I would say a better term would be <span style="font-weight: bold;">&#8216;Software Hacker&#8217;</span>.<br />
Yes that is what we do.<br />
And we are lucky to have among us a few <span style="font-weight: bold;">&#8216;Software Artists&#8217;</span> as well.</p>
<h3>Footnotes</h3>
<p><sup><a name="footnote1"></a>1</sup>: Even this may not be true. Consider the following simple function that computes sum of two integers:</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000066; font-weight: bold;">int</span> sum<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> a, <span style="color: #000066; font-weight: bold;">int</span> b<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
<span style="color: #000000; font-weight: bold;">return</span> a <span style="color: #339933;">+</span> b<span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>Even the definition of this function is tricky.<br />
This will return the sum of two numbers as long as the sum is less than Integer.MAX_INT in java. In Ruby, this will behave differently.</p>
]]></content:encoded>
			<wfw:commentRss>http://amitdev.in/blog/?feed=rss2&#038;p=11</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What make a programming language popular?</title>
		<link>http://amitdev.in/blog/?p=10</link>
		<comments>http://amitdev.in/blog/?p=10#comments</comments>
		<pubDate>Mon, 14 Jan 2008 02:37:00 +0000</pubDate>
		<dc:creator>me</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://amitdev.in/blog/?p=10</guid>
		<description><![CDATA[Recently there were many posts on programming languages (for eg. see excellent posts by Steve Yegge and Mike Vanier). That made me wonder what makes a programming language popular. Popularity seems to have no relation with the quality. Does a &#8230; <a href="http://amitdev.in/blog/?p=10">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Recently there were many posts on programming languages (for eg. see excellent posts by <a href="http://steve-yegge.blogspot.com/2007/12/codes-worst-enemy.html">Steve Yegge</a> and <a href="http://www.cs.caltech.edu/~mvanier/hacking/rants/scalable_computer_programming_languages.html">Mike Vanier</a>). That made me wonder what makes a programming language <span style="font-style: italic;">popular</span>. Popularity seems to have no relation with the <span style="font-style: italic;">quality</span>. Does a language become popular out of luck (or its <a href="http://a-nickels-worth.blogspot.com/2007/02/losing-big-is-easy.html">name</a>)? Or is there something else to it. The following is my take on what make a language popular:</p>
<p>1. Popularity<br />
The main factor that makes something popular is popularity itself. The statement may appear circular, but like <a href="http://en.wikipedia.org/wiki/Y_combinator">recursive functions</a> it is valid. When you decided to learn a new language what did you do? You would&#8217;ve read reviews, blogs etc. The more reviews you read the better. And if you are constrained by your employer this is doubly true. I agree that <a href="http://www.amazon.com/Hackers-Painters-Big-Ideas-Computer/dp/0596006624">nerds don&#8217;t care about popularity</a>. But nerds aren&#8217;t so common.</p>
<p>2. Ease of Learning<br />
The next factor is ease of learning. This is the first thing if you leave aside popularity. Btw, this may not mean the same as <a href="http://weblog.raganwald.com/2008/01/programming-language-cannot-be-better.html">intuitiveness</a>.<br />
Let&#8217;s say you have the option to learn C++ and Python. What would you choose? (Assume that you are not worried about other factors like performance etc)</p>
<p>3. Ease of Reading<br />
Interestingly ease of reading and ease of learning are not the same. For example, Perl is easy to learn (at least to get started), but exceedingly difficult to read (especially large code-bases). Some languages become popular because of the learning factor but over time lose popularity because reading (and hence maintaining) code is difficult. So this is the first major factor that determines the long term popularity of a language.</p>
<p>4. Terse<br />
<a href="http://www.codinghorror.com/blog/archives/000878.html">Smaller</a> code means easier maintenance. The ability of easily creating abstractions (using closures, macros etc) is the main factor here. But then Lisp should be more popular than java right? But remember, this is the 4th factor. And java excels in all the above factors (maybe due to the way computer science is being taught). And many people think that if it tries to add these &#8216;advanced&#8217; features it&#8217;ll become <a href="http://gafter.blogspot.com/2008/01/is-java-dying.html">dead</a>. It is unfortunate that the main factor that has to be considered in choosing a language &#8211; the level of abstraction it provides &#8211; is ignored. But then as Russel said: <span style="font-style: italic;">If fifty million people say a foolish thing, it&#8217;s still a foolish thing.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://amitdev.in/blog/?feed=rss2&#038;p=10</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Delegate using Dynamic Proxy</title>
		<link>http://amitdev.in/blog/?p=9</link>
		<comments>http://amitdev.in/blog/?p=9#comments</comments>
		<pubDate>Sun, 09 Dec 2007 09:17:00 +0000</pubDate>
		<dc:creator>me</dc:creator>
				<category><![CDATA[Duck Typing]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://amitdev.in/blog/?p=9</guid>
		<description><![CDATA[Java had the Dynamic proxy since 1.3. Somehow it is not a well known feature, maybe because the documentation is not so good. Of course there are some good articles written by Brian. Anyway I am going to show you &#8230; <a href="http://amitdev.in/blog/?p=9">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Java had the Dynamic proxy since 1.3. Somehow it is not a well known feature, maybe because the documentation is <a href="http://java.sun.com/j2se/1.3/docs/guide/reflection/proxy.html">not so good</a>. Of course there are some good articles written by <a href="http://www.ibm.com/developerworks/java/library/j-jtp08305.html">Brian</a>. Anyway I am going to show you how you can use Dynamic proxy to delegate easily.<br />
First lets imagine you want to use the features of an existing class, but keeping <a href="http://www.artima.com/lejava/articles/designprinciples4.html">good OO practices</a> in mind, you decide to use delegation. Now the problem is you need to add lot of methods just for delegating to the actual class.<br />
For eg, lets say you want to use the functionality of a List. You define your class and delegate to the actual List. It may look like this:</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyList <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">List</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">List</span> list<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> MyList<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">list</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ArrayList</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> add<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> item<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; list.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>item<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; <span style="color: #666666; font-style: italic;">//Similarly override all methods</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>This is not particularly interesting. Of course the IDEs help, but if the interface changes you need to add,recompile etc.</p>
<p>Enter Dynamic Proxy.</p>
<p>Simply put, there are two things you need to do to implement dynamic proxy. Create a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/Proxy.html">Proxy</a> (this sits between the user and your object. for eg. MyList) and create an <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/InvocationHandler.html">InvocationHandler</a> (This guy will intercept all methods and allows you to override at runtime).<br />
Before we begin, the proxy creation method is not pretty so lets have a utility method that does that for us:</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> T getProxy<span style="color: #009900;">&#40;</span>Class<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> clazz, <span style="color: #003399;">Object</span> obj<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#41;</span> <span style="color: #003399;">Proxy</span>.<span style="color: #006633;">newProxyInstance</span><span style="color: #009900;">&#40;</span>clazz.<span style="color: #006633;">getClassLoader</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #000000; font-weight: bold;">Class</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#123;</span> clazz <span style="color: #009900;">&#125;</span>, <span style="color: #000000; font-weight: bold;">new</span> Handler<span style="color: #009900;">&#40;</span>obj<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>Now we will write the Handler (which is our InvocationHandler):</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">class</span> Handler <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">InvocationHandler</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Object</span> obj<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> Handler<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> obj<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">obj</span> <span style="color: #339933;">=</span> obj<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> invoke<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> proxy, <span style="color: #003399;">Method</span> method, <span style="color: #003399;">Object</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> args<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Throwable</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">String</span> methodName <span style="color: #339933;">=</span> method.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">//Try the real object first (eg. MyList)</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">Method</span> m <span style="color: #339933;">=</span> obj.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getMethod</span><span style="color: #009900;">&#40;</span>methodName, method.<span style="color: #006633;">getParameterTypes</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> m.<span style="color: #006633;">invoke</span><span style="color: #009900;">&#40;</span>obj, args<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">NoSuchMethodException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #666666; font-style: italic;">//That failed. So try the underlying object (eg. ArrayList)</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">Method</span> m <span style="color: #339933;">=</span> method.<span style="color: #006633;">getDeclaringClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getMethod</span><span style="color: #009900;">&#40;</span>methodName, method.<span style="color: #006633;">getParameterTypes</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #003399;">Object</span> delegator <span style="color: #339933;">=</span> obj.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getMethod</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;getUnderlying&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">invoke</span><span style="color: #009900;">&#40;</span>obj<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> delegator.<span style="color: #006633;">getClass</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getMethod</span><span style="color: #009900;">&#40;</span>methodName, method.<span style="color: #006633;">getParameterTypes</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">invoke</span><span style="color: #009900;">&#40;</span>delegator, args<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">NoSuchMethodException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.<span style="color: #006633;">printStackTrace</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>Hmm, so what&#8217;s going on here?<br />
We intercept all calls to MyList and check whether it is implemented in MyList. If not, we will get the underlying object (For this we assume a method &#8216;getUnderlying&#8217; is defined on the main class. Ideally this will be passed as argument) and invoke that. Simple isn&#8217;t it?</p>
<p>Finally we don&#8217;t even have to implement List. Our class will look like:</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> MyList <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">List</span> list<span style="color: #339933;">;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> MyList<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">list</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ArrayList</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #666666; font-style: italic;">//The methods specific to this class..</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> addItem<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> item<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; list.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>item<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; &nbsp; <span style="color: #666666; font-style: italic;">//Get the delegated object</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span> getUnderlying<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> list<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></td></tr></tbody></table></div>
<p>Ok, all that looks good, but how to use it?</p>
<div class="codecolorer-container java default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:600px;"><table cellspacing="0" cellpadding="0"><tbody><tr><td style="padding:5px;text-align:center;color:#888888;background-color:#EEEEEE;border-right: 1px solid #9F9F9F;font: normal 12px/1.4em Monaco, Lucida Console, monospace;"><div>1<br />2<br />3<br />4<br /></div></td><td><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #003399;">List</span> list <span style="color: #339933;">=</span> ListProxy.<span style="color: #006633;">getProxy</span><span style="color: #009900;">&#40;</span><span style="color: #003399;">List</span>.<span style="color: #000000; font-weight: bold;">class</span>, <span style="color: #000000; font-weight: bold;">new</span> MyList<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
list.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;a&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">//add method of ArrayList</span><br />
list.<span style="color: #006633;">addItem</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;b&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> &nbsp; &nbsp;<span style="color: #666666; font-style: italic;">//addItem method of MyList</span><br />
println<span style="color: #009900;">&#40;</span>list.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">//size method of ArrayList : prints 2</span></div></td></tr></tbody></table></div>
<p>What have we done?<br />
1. We used delegation without the pain of overriding all methods which have default behavior.<br />
2. We used <a href="http://en.wikipedia.org/wiki/Duck_typing">Duck typing</a> (Though MyList does not implement List, we can use it as a List).<br />
3. This code is generic and can be used for any interface/class delegation.</p>
<p>Thats all for now, folks!</p>
]]></content:encoded>
			<wfw:commentRss>http://amitdev.in/blog/?feed=rss2&#038;p=9</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

