<?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>Bold dream &#187; Programming</title>
	<atom:link href="http://bolddream.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://bolddream.com</link>
	<description>Imagination is limitless. So is stupidity.</description>
	<lastBuildDate>Tue, 02 Mar 2010 22:42:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Getting a random row from a relational database</title>
		<link>http://bolddream.com/2010/01/22/getting-a-random-row-from-a-relational-database/</link>
		<comments>http://bolddream.com/2010/01/22/getting-a-random-row-from-a-relational-database/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 16:22:55 +0000</pubDate>
		<dc:creator>Emil Vladev</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://bolddream.com/?p=258</guid>
		<description><![CDATA[Problem From time to time one needs to fetch a random row from a table in a db. Solution Take one The &#8220;obvious&#8221; solution is to order by RAND() and get the first: SELECT * FROM users ORDER BY RAND&#40;&#41; LIMIT 1; /* Don't do that */ It does the job, problem solved! Well, no, [...]]]></description>
			<content:encoded><![CDATA[<h3>Problem</h3>
<p>From time to time one needs to fetch a random row from a table in a db. </p>
<h3>Solution</h3>
<h4>Take one</h4>
<p>The &#8220;obvious&#8221; solution is to order by <code>RAND()</code> and get the first:</p>

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> users <span style="color: #993333; font-weight: bold;">ORDER</span> <span style="color: #993333; font-weight: bold;">BY</span> RAND<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">LIMIT</span> <span style="color: #cc66cc;">1</span>; <span style="color: #808080; font-style: italic;">/* Don't do that */</span></pre></div></div>

<p>It does the job, problem solved!</p>
<p>Well, no, not exactly! While it works, the performance will be awful for any table of significant size.</p>
<h4>Take two</h4>
<p>There is another, simple, but efficient, method to get a random row:</p>
<ol>
<li>Fetch the number of rows using <code>COUNT()</code>.

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> COUNT<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">*</span><span style="color: #66cc66;">&#41;</span> <span style="color: #993333; font-weight: bold;">FROM</span> users;</pre></div></div>

</li>
<li>Get a random positive number, that is less than (but not equal) to that count.</li>
<li>Select the row using <code>OFFSET</code> (on <a href="http://www.mysql.com/">MySQL</a> &#8211; there are ways to do the same on all major RDBMS)

<div class="wp_syntax"><div class="code"><pre class="sql" style="font-family:monospace;"><span style="color: #993333; font-weight: bold;">SELECT</span> <span style="color: #66cc66;">*</span> <span style="color: #993333; font-weight: bold;">FROM</span> users <span style="color: #993333; font-weight: bold;">LIMIT</span> <span style="color: #cc66cc;">1</span> OFFSET :rand</pre></div></div>

<p> where <code>:rand</code> is the number you computed.
</li>
</ol>
<p>While this uses two queries &#8211; both of them are very efficient.</p>
<p>Here is the concrete code on how to do that in <a href="http://www.djangoproject.com/">Django</a> (using a <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#id2">custom manager</a>):</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">class</span> UsersManager<span style="color: black;">&#40;</span>models.<span style="color: black;">Manager</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #dc143c;">random</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        count = <span style="color: #008000;">self</span>.<span style="color: black;">aggregate</span><span style="color: black;">&#40;</span>count=Count<span style="color: black;">&#40;</span><span style="color: #483d8b;">'id'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'count'</span><span style="color: black;">&#93;</span>
        random_index = randint<span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, count - <span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: #008000;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span>random_index<span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> User<span style="color: black;">&#40;</span>models.<span style="color: black;">Model</span><span style="color: black;">&#41;</span>:
    objects = UsersManager<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #808080; font-style: italic;"># ... [fields] ...</span></pre></div></div>

<p>Usage is as simple as</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">User.<span style="color: black;">objects</span>.<span style="color: #dc143c;">random</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Just for the record &#8211; the Django way to <strike>shoot yourself in the foot</strike> do <code>ORDER BY RAND()</code> is</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">User.<span style="color: black;">objects</span>.<span style="color: black;">order_by</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'?'</span><span style="color: black;">&#41;</span>  <span style="color: #808080; font-style: italic;"># If you do that in production - you may as well forget about sleep!</span></pre></div></div>

<h3>Proof</h3>
<p>Here is the evidence that doing <code>ORDER BY RAND()</code> is very slow.</p>
<p>For the test we will have a simple Django model and a few of scripts &#8211; one that populates the database with bulk data, one that fetches a user using <code>ORDER BY RAND()</code> and one that fetches it using a second query. We populate the db with one million records and get a random one.</p>
<p>Here are the results (done using Python 2.6.4 and MySQL 5.1/SQLite 3.6.16 on Ubuntu 9.10):</p>
<p>Using the naive method by doing <code>ORDER BY RAND()</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #000000; font-weight: bold;">time</span> python naive.py
<span style="color: #666666; font-style: italic;">#       MySQL        SQLite</span>
real	0m4.519s     0m2.061s <span style="color: #666666; font-style: italic;"># seconds?!?! </span>
user	0m0.152s     0m1.952s
sys	0m0.028s     0m0.056s</pre></div></div>

<p>(executing the query directly results in times close to those).</p>
<p>Using the smart method with two queries:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">$ <span style="color: #000000; font-weight: bold;">time</span> python smart.py 
<span style="color: #666666; font-style: italic;">#       MySQL        SQLite</span>
real	0m0.367s     0m0.339s <span style="color: #666666; font-style: italic;"># much better</span>
user	0m0.156s     0m0.284s
sys	0m0.032s     0m0.052s</pre></div></div>

<p>The more records you add to the table, the slower the naive method will get, while the smart one will run at about the same speed.</p>
<p>If you need to get a random record out of a filtered set (using <code>WHERE</code>) is&#8217;s basically the same. You just need to add the <code>WHERE</code> clause to both queries.</p>
<h4>Details</h4>
<p>Below is the code that is used to make the benchmark.</p>
<p>This is the <code>models.py</code> file of a simple Django app.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">from</span> <span style="color: #dc143c;">random</span> <span style="color: #ff7700;font-weight:bold;">import</span> randint
<span style="color: #ff7700;font-weight:bold;">from</span> django.<span style="color: black;">db</span> <span style="color: #ff7700;font-weight:bold;">import</span> models
<span style="color: #ff7700;font-weight:bold;">from</span> django.<span style="color: black;">db</span>.<span style="color: black;">models</span> <span style="color: #ff7700;font-weight:bold;">import</span> Count
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> UserManager<span style="color: black;">&#40;</span>models.<span style="color: black;">Manager</span><span style="color: black;">&#41;</span>:
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #dc143c;">random</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        count = <span style="color: #008000;">self</span>.<span style="color: black;">aggregate</span><span style="color: black;">&#40;</span>ids=Count<span style="color: black;">&#40;</span><span style="color: #483d8b;">'id'</span><span style="color: black;">&#41;</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'ids'</span><span style="color: black;">&#93;</span>
        random_index = randint<span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, count - <span style="color: #ff4500;">1</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: #008000;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span>random_index<span style="color: black;">&#93;</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> random_naive<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: #008000;">all</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>.<span style="color: black;">order_by</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'?'</span><span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> User<span style="color: black;">&#40;</span>models.<span style="color: black;">Model</span><span style="color: black;">&#41;</span>:
    username = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">128</span><span style="color: black;">&#41;</span>
    password = models.<span style="color: black;">CharField</span><span style="color: black;">&#40;</span>max_length=<span style="color: #ff4500;">128</span><span style="color: black;">&#41;</span>
&nbsp;
    objects = UserManager<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>The <code>bluk.py</code> script that will fill the db with junk.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
<span style="color: #ff7700;font-weight:bold;">import</span> settings
&nbsp;
<span style="color: #dc143c;">os</span>.<span style="color: black;">environ</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'DJANGO_SETTINGS_MODULE'</span><span style="color: black;">&#93;</span> = <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>
    <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">dirname</span><span style="color: black;">&#40;</span>__file__<span style="color: black;">&#41;</span>, <span style="color: #483d8b;">'settings'</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">from</span> users.<span style="color: black;">models</span> <span style="color: #ff7700;font-weight:bold;">import</span> User
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    <span style="color: #ff7700;font-weight:bold;">for</span> i <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">range</span><span style="color: black;">&#40;</span><span style="color: #ff4500;">0</span>, <span style="color: #ff4500;">1000000</span><span style="color: black;">&#41;</span>:
        u = User<span style="color: black;">&#40;</span>username=<span style="color: #483d8b;">&quot;user{0}&quot;</span>.<span style="color: black;">format</span><span style="color: black;">&#40;</span>i<span style="color: black;">&#41;</span>, password=<span style="color: #483d8b;">&quot;pass{0}&quot;</span>.<span style="color: black;">format</span><span style="color: black;">&#40;</span>i<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        u.<span style="color: black;">save</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>This is <code>naive.py</code> &#8211; the script that uses the slow method.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
<span style="color: #ff7700;font-weight:bold;">import</span> settings
&nbsp;
<span style="color: #dc143c;">os</span>.<span style="color: black;">environ</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'DJANGO_SETTINGS_MODULE'</span><span style="color: black;">&#93;</span> = <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>
    <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">dirname</span><span style="color: black;">&#40;</span>__file__<span style="color: black;">&#41;</span>, <span style="color: #483d8b;">'settings'</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">from</span> users.<span style="color: black;">models</span> <span style="color: #ff7700;font-weight:bold;">import</span> User
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    u = User.<span style="color: black;">objects</span>.<span style="color: black;">random_naive</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span><span style="color: black;">&#40;</span>u.<span style="color: black;">username</span><span style="color: black;">&#41;</span></pre></div></div>

<p>And <code>smart.py</code> that uses an additional query.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">os</span>
<span style="color: #ff7700;font-weight:bold;">import</span> settings
&nbsp;
<span style="color: #dc143c;">os</span>.<span style="color: black;">environ</span><span style="color: black;">&#91;</span><span style="color: #483d8b;">'DJANGO_SETTINGS_MODULE'</span><span style="color: black;">&#93;</span> = <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span>
    <span style="color: #dc143c;">os</span>.<span style="color: black;">path</span>.<span style="color: black;">dirname</span><span style="color: black;">&#40;</span>__file__<span style="color: black;">&#41;</span>, <span style="color: #483d8b;">'settings'</span><span style="color: black;">&#41;</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">from</span> users.<span style="color: black;">models</span> <span style="color: #ff7700;font-weight:bold;">import</span> User
&nbsp;
<span style="color: #ff7700;font-weight:bold;">if</span> __name__ == <span style="color: #483d8b;">'__main__'</span>:
    u = User.<span style="color: black;">objects</span>.<span style="color: #dc143c;">random</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    <span style="color: #ff7700;font-weight:bold;">print</span><span style="color: black;">&#40;</span>u.<span style="color: black;">username</span><span style="color: black;">&#41;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://bolddream.com/2010/01/22/getting-a-random-row-from-a-relational-database/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Sending null to /dev/null</title>
		<link>http://bolddream.com/2009/06/12/sending-null-to-devnull/</link>
		<comments>http://bolddream.com/2009/06/12/sending-null-to-devnull/#comments</comments>
		<pubDate>Fri, 12 Jun 2009 07:05:57 +0000</pubDate>
		<dc:creator>Emil Vladev</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://bolddream.com/?p=44</guid>
		<description><![CDATA[In a recent talk at QCon labeled Null References: The Billion Dollar Mistake1, Sir Charles Antony Richard Hoare himself &#8211; the inventor of Null (and QuickSort, and many other things that shaped our industry) states that Null was/is a bad idea. What is Null? Here is an explanation from wikipedia. Null is a special pointer [...]]]></description>
			<content:encoded><![CDATA[<p>In a recent talk at QCon labeled <a href="http://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare"><q>Null References: The Billion Dollar Mistake</q></a><sup>1</sup>, <a href="http://en.wikipedia.org/wiki/C._A._R._Hoare">Sir Charles Antony Richard Hoare</a> himself &#8211; the inventor of Null (and QuickSort, and many other things that shaped our industry) states that Null was/is a bad idea.</p>
<h3>What is Null?</h3>
<p>Here is an <a href="http://en.wikipedia.org/wiki/Null_(computer_programming)">explanation from wikipedia</a>.</p>
<blockquote><p>
Null is a special pointer value (or other kind of object reference) used to signify that a pointer intentionally does not point to (or refer to) an object.
</p></blockquote>
<p>From an object oriented language point of view Null is a a value, whose type is a subclass of every other type in the system. It&#8217;s always at the bottom of the hierarchy. Because of this and the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov substitution principle</a> Null can be used everywhere normally other type would be used. Have a method, that is marked to return string? It can return Null.</p>
<h3>What is the problem with Null</h3>
<p>The problem with it is that every method can return Null. And you, as a consumer of that method, need to check every time if the return value is Null. If you don&#8217;t &#8211; you (usually) get a Null pointer exception and your program crashes.</p>
<p>Now, exceptions are a very good tool &#8211; but particularly the Null pointer exception is a bad thing. Why? Because if it bubbles more than one level up it&#8217;s a sign of a leaky abstraction. Let me back up this claim:</p>
<p>First, what does a Null pointer exception mean? Let&#8217;s have a look at the <a href="http://java.sun.com/javase/6/docs/api/java/lang/NullPointerException.html">documentation of it in Java</a>:</p>
<blockquote><p>
Thrown when an application attempts to use null in a case where an object is required. These include:</p>
<ul>
<li>Calling the instance method of a null object.</li>
<li>Accessing or modifying the field of a null object.</li>
<li>Taking the length of null as if it were an array.</li>
<li>Accessing or modifying the slots of null as if it were an array.</li>
<li>Throwing null as if it were a Throwable value.</li>
</ul>
</blockquote>
<p>Basically it says that an object is expected, but no such is provided. Well, this is an implementation detail. In your business logic I hardly believe that you will be talking about references and such. We usually talk about real world object like people, accounts, etc. Any method that throws a Null pointer exception unveils parts of its implementation.</p>
<p>How many times has happened to you to forget to fill a field in some form and get a Null pointer exception.<br />
<q>I forgot to write my email &#8211; what does that Null thing has to do with it?!?</q></p>
<p>A method should never throw Null pointer exceptions (I&#8217;ve seen people doing it) &#8211; an Illegal argument exception is a much better one. Most of the time the underlying platform is the one throwing Null pointer exceptions. </p>
<p>It&#8217;s just a convention, but Null pointer exceptions should be extinguished when sighted.</p>
<p>So&#8230;</p>
<h3>How can we handle Null</h3>
<h4>Take 1</h4>
<p>The most straightforward and wide spread solution is to tell everyone to check the values for Null references. But that is a blacklist approach and, for this kind of problem, it doesn&#8217;t work. People forget stuff &#8211; and sooner or later someone will forget to do it and your 24/7 program will crash at 3AM on Sunday. Unit testing can help a lot here, but it requires work and you still cannot be 100% sure.</p>
<p>Can we do better?</p>
<h4>Take 2</h4>
<p>I would like to point out that the following method makes more sense in a statically typed language, where you have a compiler, checking your types for validity.</p>
<p>Most of the time we return Null as a value from a method that we want to return nothing, but some return value is expected and we throw Null at it.</p>
<p>Let&#8217;s have a look at the following Java code:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> tld<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> domain<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">int</span> dot <span style="color: #339933;">=</span> domain.<span style="color: #006633;">lastIndexOf</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'.'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>dot <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span> <span style="color: #339933;">||</span> dot <span style="color: #339933;">==</span> domain.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> domain.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span>dot <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The method above returns the top level domain part, or null if none found.<br />
The &#8220;right&#8221; user code of this method is like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span> d <span style="color: #339933;">=</span> tld<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;example.org&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>d <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Save to database</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Show the user a message</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>But, as I pointed out earlier &#8211; there will be time that you will forget to make the check and the user will see a nasty exception, leaving him clueless about what she did wrong.</p>
<p>What we can do instead is signify our intentions that we might not return a value.<br />
In <a href="http://scala-lang.org/">Scala</a>, we have the <a href="http://www.scala-lang.org/docu/files/api/scala/Option.html"><code>Option</code></a> class &#8211; heavily inspired by <a href="http://www.haskell.org/">Haskell</a>&#8216;s <a href="http://www.haskell.org/all_about_monads/html/maybemonad.html"><code>Maybe</code></a> monad.<br />
The <code>Option</code> class has two (final) subclasses<sup>2</sup>: <a href="http://www.scala-lang.org/docu/files/api/scala/Some.html"><code>Some</code></a> and <a href="http://www.scala-lang.org/docu/files/api/scala/None$object.html"><code>None</code></a>. You return <code>Some</code> when you have something to return and <code>None</code> when you don&#8217;t.<br />
Let&#8217;s look at the <code>tld</code> method implemented in Scala using the <code>Option</code> class:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> tld<span style="color: #F78811;">&#40;</span>domain<span style="color: #000080;">:</span> String<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> Option<span style="color: #F78811;">&#91;</span>String<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">val</span> dot <span style="color: #000080;">=</span> domain lastIndexOf <span style="color: #6666FF;">'.'</span>
  <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>dot <span style="color: #000080;">==</span> -<span style="color: #F78811;">1</span> || dot <span style="color: #000080;">==</span> domain.<span style="color: #000000;">length</span><span style="color: #F78811;">&#41;</span> None
  <span style="color: #0000ff; font-weight: bold;">else</span> Some<span style="color: #F78811;">&#40;</span>domain.<span style="color: #000000;">substring</span><span style="color: #F78811;">&#40;</span>dot + <span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>And the usage if it:</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">val</span> com<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span> tld<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;example.com&quot;</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">getOrElse</span><span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;unknown&quot;</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<p>That line above will return either the tld part the domain or <code>"unknown"</code> if none is found. Concise, isn&#8217;t it?<br />
If we omit the <code>getOrElse</code> part the compiler with complain the we are not giving it a <code>String</code> value, but <code>None</code> instead.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #008000; font-style: italic;">// Does not compile!</span>
<span style="color: #0000ff; font-weight: bold;">val</span> com<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span> tld<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;example.com&quot;</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<p>That way we are able to catch the error early (say 17:00 o&#8217;clock on Friday which is much better than 3:00 in the morning on Sunday).</p>
<p>What we&#8217;ve done? We told the type system that we might return a value, but not necessary. Specifying the return type of tld to be <code>Option[String]</code> instead of just <code>String</code> does just that.</p>
<p>So&#8230; Can we do that in Java?</p>
<p>Let&#8217;s give it a try.<br />
We&#8217;ll have a <code>JOption</code> interface with <code>JSome</code> and <code>JNone</code> implementing classes:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">interface</span> JOption<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> isEmpty<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> T getOrElse<span style="color: #009900;">&#40;</span>T other<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The <code>JNone</code> class will mark the lack of value.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JNone<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> <span style="color: #000000; font-weight: bold;">implements</span> JOption<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> JNone<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> isEmpty<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">true</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> T getOrElse<span style="color: #009900;">&#40;</span>T other<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> other<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>and the <code>JSome</code> class &#8211; the presence of it.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> JSome<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> <span style="color: #000000; font-weight: bold;">implements</span> JOption<span style="color: #339933;">&lt;</span>T<span style="color: #339933;">&gt;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> T value<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> JSome<span style="color: #009900;">&#40;</span>T value<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">value</span> <span style="color: #339933;">=</span> value<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> isEmpty<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">false</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> T getOrElse<span style="color: #009900;">&#40;</span>T other<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> value<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And now our revised <code>tld</code> method, using the new <code>JOption</code> machinery:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> JOption<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span> tld<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> domain<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">int</span> dot <span style="color: #339933;">=</span> domain.<span style="color: #006633;">lastIndexOf</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'.'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>dot <span style="color: #339933;">==</span> <span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span> <span style="color: #339933;">||</span> dot <span style="color: #339933;">==</span> domain.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> JNone<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #000000; font-weight: bold;">new</span> JSome<span style="color: #339933;">&lt;</span>String<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#40;</span>domain.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span>dot <span style="color: #339933;">+</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>And using it becomes:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">String</span> com <span style="color: #339933;">=</span> tld<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;example&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">getOrElse</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unknown&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The <code>tld</code> method isn&#8217;t longer than our original Null-returning version, but now the compiler will help us, because if we write:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Does not even compile</span>
<span style="color: #003399;">String</span> com <span style="color: #339933;">=</span> tld<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;example&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>we&#8217;ll get a compiler error.</p>
<h3>Final thoughts</h3>
<p>The proposed method probably isn&#8217;t the best and can be improved<sup>3</sup>, but it illustrates the concept.</p>
<p>Also, while this solution might help, the Null value still exists and people <del datetime="2009-06-09T08:30:02+00:00">can</del>will (ab)use it.<br />
Scala has a Null value as well &#8211; for compatibility with Java.</p>
<p>On the bright side &#8211; Haskell, Erlang and other functional languages don&#8217;t have anything like Null in them and use some form of the described approach.</p>
<p>But on the dark side we have Javascript &#8211; there you have <code>undefined</code>, <code>null</code> and <code>NaN</code> that adds even more <a href="http://www.amazon.com/gp/product/0735619670?ie=UTF8&#038;tag=bolddream-20&#038;linkCode=as2&#038;camp=1789&#038;creative=390957&#038;creativeASIN=0735619670">codding horror</a><img src="http://www.assoc-amazon.com/e/ir?t=bolddream-20&#038;l=as2&#038;o=1&#038;a=0735619670" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />. <a href="http://www.infoq.com/news/2009/06/FSharp-Nulls">F# is in similar state.</a></p>
<p>Please, share your thoughts bellow.<br />
__________________<br />
<sup>1</sup> On 25 August 2009 InfoQ published the video.<br />
<sup>2</sup> To be precise, None is an object (a singleton in Scala).<br />
<sup>3</sup> We can also add other methods to JOption like get() that will throw an exception in the case of JNone and return the value for JSome, as well as a proper equals implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://bolddream.com/2009/06/12/sending-null-to-devnull/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>The unemployed developer &#8211; a tale with expected end</title>
		<link>http://bolddream.com/2009/05/30/the-unemployed-developer-a-tale-with-expected-end/</link>
		<comments>http://bolddream.com/2009/05/30/the-unemployed-developer-a-tale-with-expected-end/#comments</comments>
		<pubDate>Sat, 30 May 2009 09:19:04 +0000</pubDate>
		<dc:creator>Emil Vladev</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://bolddream.com/?p=49</guid>
		<description><![CDATA[Today is a great day for John. He has just got a job as a programmer in MegaCorp138. He is 22 years old and a whole new world opens up in front of him. He will meet a lot of new people, get good salary, and most importantly, program in The Language. John studied programming [...]]]></description>
			<content:encoded><![CDATA[<p>Today is a great day for John. He has just got a job as a programmer in MegaCorp138. He is 22 years old and a whole new world opens up in front of him. He will meet a lot of new people, get good salary, and most importantly, program in The Language. John studied programming through The Language. He finds The Language as the best piece of software in the world.</p>
<div id="attachment_117" class="wp-caption alignright" style="width: 210px"><img class="size-full wp-image-117" title="Megacorp138 HQ" src="http://bolddream.com/wp-content/uploads/2009/05/enterprise.jpg" alt="Megacorp138 HQ" width="200" height="267" /><p class="wp-caption-text">Megacorp138 HQ</p></div>
<p>Time goes by, John is now 28 and he is a leader of a small team, working on a very interesting project, which they have just started. From scratch! Life could not be better…</p>
<p>Unfortunately, soon things start to become worse. The time passes by and the project is delayed many times. Eventually it goes into production, but the users are finding new and strange bugs every day. In time all of the developers get frustrated and quit. John is now The Man of The Project. He knows (almost) everything about it and is a master of The Language.</p>
<p>Now John has kids, a house, a couple of cars, and even a better paid job. The project he was in charge of is now cleared of bugs, he knows most of the pieces in it, but from time to time there are some surprises that he does not expect.</p>
<p>John is 39. A new start-up comes along claiming that they have better product than the one John has developed.<br />
<q>Aah, we can crush them! They have nothing better than us</q> &#8212; that was the mood in the company.</p>
<p>Few years fly by. The start-up is still doing well. The mood in MegaCorp138 has slightly changed to: <q>We are much bigger and stronger than them. They have some extra features we don’t have, but we’ll beat them</q>. John is the Head of the programming department now.</p>
<p>After few more years and some mood changes, MegaCorp138 is near to bankruptcy. The owners of the company decide to sell it to that small start-up they thought they will crush. John gets laid off.</p>
<p>John is 51 now, looking for a new job in the programming world. But he is having a very hard time in finding a new job, and, most importantly &#8211; he has no clue why? All these people are asking for completely different skills. John has been programming in The Language. He knows every single part of it. Of course, while he was working in MegaCorp138, now and then, a young chap would come and told him:</p>
<div id="attachment_122" class="wp-caption alignright" style="width: 110px"><br />
<a href="http://www.amazon.com/gp/product/0131495054?ie=UTF8&amp;tag=bolddream-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0131495054"><img class="size-full wp-image-122" title="xUnit Test Patterns" src="http://bolddream.com/wp-content/uploads/2009/05/xunit1.jpg" alt="xUnit Test Patterns" width="100" height="135" /></a><img style="border:none !important; margin:0px !important;" src="http://www.assoc-amazon.com/e/ir?t=bolddream-20&amp;l=as2&amp;o=1&amp;a=0131495054" border="0" alt="" width="1" height="1" /><br />
<p class="wp-caption-text">xUnit Test Patterns</p></div>
<blockquote><p>&#8211; You should learn at least one new language per year.<br />
&#8211; Why should I learn a new language? I’m using The Language!</p></blockquote>
<p>Another chap tried to convince him to write tests.</p>
<blockquote><p>Tests? I know The Language and The Product from inside and out. I don’t need tests. I’ve tested it and &#8211; here &#8211; it works. It’s on my screen. I don’t have the time to write 50% more code. I’m way too busy.</p></blockquote>
<p>Those were commonplace pieces of advice to John.</p>
<p>Here is John today, still looking for a job. At one of the interviews the interviewer tells him a story.</p>
<blockquote><p>A man was walking through the forest when he noticed a woodcutter. The man went closer and saw that the saw of the woodcutter was very blunt.<br />
&#8211; Hey, your saw is very blunt. Why don’t you stop and sharpen it?<br />
&#8211; STOP and sharpen it? &#8212; the woodcutter responded rudely &#8212; Can’t you see that I have a lot of work to do?</p></blockquote>
<p><q>What a stupid woodcutter!</q>, thought John.</p>
<p>Are you That woodcutter? Or That John?</p>
<p><span style="color: #999999;">___________<br />
Many thanks to Nas OOD for reviewing this post.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://bolddream.com/2009/05/30/the-unemployed-developer-a-tale-with-expected-end/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Scala presentation @ initCamp</title>
		<link>http://bolddream.com/2009/05/29/scala-presentation-initcamp/</link>
		<comments>http://bolddream.com/2009/05/29/scala-presentation-initcamp/#comments</comments>
		<pubDate>Fri, 29 May 2009 07:40:15 +0000</pubDate>
		<dc:creator>Emil Vladev</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[initCamp]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://bolddream.com/?p=79</guid>
		<description><![CDATA[Last night I did a presentation on Scala @ initCamp. This was my first presentation I&#8217;ve ever given. And I don&#8217;t know a word to describe it. So I&#8217;ll just use this one: Awesome. A very good discussion happened, people grasped most of my talk (or at least I think so?) and the examples. It [...]]]></description>
			<content:encoded><![CDATA[<p>Last night I did a presentation on <a href="http://scala-lang.org">Scala</a> @ <a href="http://initlab.startup-bg.org/?p=226">initCamp</a>. This was my first presentation I&#8217;ve ever given. And I don&#8217;t know a word to describe it. So I&#8217;ll just use this one: <strong>Awesome</strong>. A very good discussion happened, people grasped most of my talk (or at least I think so?) and the examples. It was a very, very good experience.</p>
<p><a href="http://skanev.com/">Stefan&#8217;s</a> talk about Ruby was <strong>on the target</strong> as usual. He is a very talented presenter and to be perfectly fair, I&#8217;ve seen him presenting before and borrowed (stolen) some ideas from him :), but mostly I got ideas from his source &#8211; the Ruby community &#8211; they are probably the best community when it comes to marketing and entertainment (and many other things as well).</p>
<p>The third part was a discussion about &#8220;The perfect programming language&#8221;. To be perfectly honest I didn&#8217;t understand some parts of it, but that was probably due to the fact that I was very tired.<br />
Basically, what I could conclude is that Lisp seems to be an excellent language, with (way (too (many) (parenthesis))). :)</p>
<p>Here are the most important links from my presentation:</p>
<ul>
<li><a href="http://video.google.com/videoplay?docid=-8860158196198824415">Growing a langauge, by Guy Steele</a> &#8211; an incredible talk by Guy Steele about programming in general!</li>
<li><a href="http://scala-lang.org">The Scala Programming Langauge</a></li>
<li><a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=scala+neward">The busy Java developer&#8217;s guide to Scala</a></li>
<li><a href="http://programming-scala.labs.oreilly.com/">O&#8217;Reilly &#8220;Programming Scala&#8221;</a> &#8211; an early preview of a book about Scala from O&#8217;Reilly.</li>
<li><a href="http://www.parleys.com/display/PARLEYS/The+Feel+Of+Scala">The Feel of Scala</a> &#8211; A great talk on Scala by one of the core developers.</li>
</ul>
<p>I would be happy to answer to any questions you have.</p>
<p>Below are the slides of the presentation. Basically only the code examples. I&#8217;ve removed the images and the jokes as they make little sense without context:</p>
<div id="__ss_1505955" style="width: 425px; text-align: left;"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" title="Scala 2 + 2 &gt; 4" href="http://www.slideshare.net/vladev/scala-2-2-4-1505955?type=presentation">Scala 2 + 2 &gt; 4</a><object width="425" height="355" data="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=scala-2and2gt4trimmed-090529071357-phpapp02&amp;stripped_title=scala-2-2-4-1505955" type="application/x-shockwave-flash"><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="src" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=scala-2and2gt4trimmed-090529071357-phpapp02&amp;stripped_title=scala-2-2-4-1505955" /><param name="allowfullscreen" value="true" /></object></p>
<div style="font-size: 11px; font-family: tahoma,arial; height: 26px; padding-top: 2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">Keynote presentations</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/vladev">Emil Ivanov</a>.</div>
</div>
<p>Take care.</p>
]]></content:encoded>
			<wfw:commentRss>http://bolddream.com/2009/05/29/scala-presentation-initcamp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Bending a language to your will</title>
		<link>http://bolddream.com/2009/05/25/bending-a-language-to-your-will/</link>
		<comments>http://bolddream.com/2009/05/25/bending-a-language-to-your-will/#comments</comments>
		<pubDate>Mon, 25 May 2009 06:00:12 +0000</pubDate>
		<dc:creator>Emil Vladev</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://bolddream.com/?p=18</guid>
		<description><![CDATA[Just watched the talk by Guy Steele &#8211; Growing a language. In it, he points out that a language should be designed to grow, rather than have many features. It should have just the right amount of tools, that will help users create more tools on top of the existing ones. The interesting thing is [...]]]></description>
			<content:encoded><![CDATA[<p>Just watched the talk by Guy Steele &#8211; <a href="http://video.google.com/videoplay?docid=-8860158196198824415">Growing a language</a>. In it, he points out that a language should be designed to grow, rather than have many features. It should have just the right amount of tools, that will help users create more tools on top of the existing ones.<br />
The interesting thing is that this talk is from 1999. He advocates about expanding the Java Programming Language by adding Generics and operator overloading to it.</p>
<p>Here are we now, 2009, the Java language does have generics, which seem not thought well enough<sup>1</sup>, but doesn&#8217;t have operator overloading. It may never have it.<br />
And here are we again, 2009, we have the <a href="http://www.scala-lang.org/">Scala Programming Language</a>. It can satisfy both requirements Guy mentions explicitly &#8211; operator overloading and generics. But Scala has pushed these concepts further.<br />
Actually, it doesn&#8217;t have operator overloading &#8211; it has a way to do operator overloading by allowing people to define methods that look like operators.<br />
Compare the use of Java&#8217;s BigInteger class</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">import</span> java.<span style="color: #000000;">math</span>.<span style="color: #000000;">BigInteger</span>
<span style="color: #0000ff; font-weight: bold;">def</span> factorial<span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">:</span> BigInteger<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> BigInteger <span style="color: #000080;">=</span>
  <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>x <span style="color: #000080;">==</span> BigInteger.<span style="color: #000000;">ZERO</span><span style="color: #F78811;">&#41;</span>
    BigInteger.<span style="color: #000000;">ONE</span>
  <span style="color: #0000ff; font-weight: bold;">else</span>
    x.<span style="color: #000000;">multiply</span><span style="color: #F78811;">&#40;</span>factorial<span style="color: #F78811;">&#40;</span>x.<span style="color: #000000;">subtract</span><span style="color: #F78811;">&#40;</span>BigInteger.<span style="color: #000000;">ONE</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<p>and Scala&#8217;s wrapped version &#8211; BigInt</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> factorial<span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">:</span> BigInt<span style="color: #F78811;">&#41;</span><span style="color: #000080;">:</span> BigInt <span style="color: #000080;">=</span>
  <span style="color: #0000ff; font-weight: bold;">if</span> <span style="color: #F78811;">&#40;</span>x <span style="color: #000080;">==</span> <span style="color: #F78811;">0</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">1</span> <span style="color: #0000ff; font-weight: bold;">else</span> x <span style="color: #000080;">*</span> factorial<span style="color: #F78811;">&#40;</span>x - <span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<p>It looks natural, clean and concise<sup>2</sup>.</p>
<p>Scala also has generics, but, yet again, pushed one idea further. They are called type parameters. Just like a method may receive objects as parameters, the same way it may receive types as parameters. This allows one to write methods (or classes) in a way that they work with any or some types without explicitly defining behavior for each supported type and puts the control in the hands of the developer that writes the class.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">object</span> Queue <span style="color: #F78811;">&#123;</span>
  <span style="color: #008000; font-style: italic;">// constructs a queue with initial elements ‘xs’</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> apply<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>xs<span style="color: #000080;">:</span> T<span style="color: #000080;">*</span><span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> Queue<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>xs.<span style="color: #000000;">toList</span>, Nil<span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>Here both the class Queue and the method apply are parametrized by type [T]<sup>2</sup>.</p>
<p>Growing your language is not a new idea &#8211; in 1993, Paul Graham wrote about <a href="http://www.paulgraham.com/progbot.html">Bottom-up programming</a> where he proudly stands behind this idea that a language should grow with the user and be grown by the user. Lisp have had this for <del>years</del> decades, but for (some (strange (reason))) never hit mainstream<sup>3</sup>.</p>
<p>A couple of years ago all this fuzz about <a href="http://ruby-lang.org">Ruby</a> and Domain Specific Languages, Internal Domain Specific Languages to be precise, hit the scene. And Ruby has a lot of ideas from Lisp in it, but with better syntax.</p>
<p>Ultimately, the perfect language will be one with no primitives &#8211; everything can be defined as a library and the language will be able to be grown by it&#8217;s users, but not one that is ultimately flexible as it will produce very different and divergent styles with <a href="http://github.com/raganwald/homoiconic/blob/master/2009-04-08/sick.md#readme">hard-to-cache errors</a>. In my opinion Scala is the one that stand the best chance of satisfying those requirements.</p>
<p>__________________<br />
<sup>1</sup> Try using wildcards in a combination of framework and user code, where you do not own both.<br />
<sup>2</sup> Examples are provided for completeness and not explained as their explanation will blur the main topic of this post.<br />
<sup>3</sup> Lisp being mainstream or not is arguable, without defining &#8220;mainstream&#8221;, but even it&#8217;s most passionate defenders will agree that in terms of popularity in can do a lot better.</p>
]]></content:encoded>
			<wfw:commentRss>http://bolddream.com/2009/05/25/bending-a-language-to-your-will/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
