<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><!-- generator="wordpress/2.3.1" --><rss 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/" version="2.0">

<channel>
	<title>thomasknierim.com</title>
	<link>http://www.thomasknierim.com</link>
	<description>Software development with Java, Scala, and PHP</description>
	<pubDate>Fri, 15 May 2009 03:45:38 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.1</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/thomasknierim" type="application/rss+xml" /><item>
		<title>Scala Currency Class</title>
		<link>http://www.thomasknierim.com/114/scala/scala-currency-class/</link>
		<comments>http://www.thomasknierim.com/114/scala/scala-currency-class/#comments</comments>
		<pubDate>Mon, 11 May 2009 04:13:39 +0000</pubDate>
		<dc:creator>thomas</dc:creator>
		
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.thomasknierim.com/114/scala/scala-currency-class/</guid>
		<description><![CDATA[Most of you probably ran into the well-known precision problems with floating point numbers at one time or another. If you haven&#8217;t, consider this example:

1
2
scala&#62; 1.2 - 1.0
res1: Double = 0.19999999999999996

Oops. Shouldn&#8217;t that be 0.2? Yes it should, but since the number 0.2 cannot be represented exactly in binary form, the result is a little [...]]]></description>
			<content:encoded><![CDATA[<p>Most of you probably ran into the well-known precision problems with floating point numbers at one time or another. If you haven&#8217;t, consider this example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> <span style="color: #F78811;">1.2</span> - <span style="color: #F78811;">1.0</span>
res1<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Double</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">0.19999999999999996</span></pre></td></tr></table></div>

<p>Oops. Shouldn&#8217;t that be 0.2? Yes it should, but since the number 0.2 cannot be represented exactly in binary form, the result is a little bit less. This problem becomes annoying when Floats or Double values are used to represent money. It gets worse when multiplication or division operations magnify the error, as for example in the case of interest calculations. Simply put, you can&#8217;t guarantee the exactness of calculations down to the cent when you represent monetary amounts as floating point values. The Java language has a type called BigDecimal which solves this problem. It offers arbitrary scale fixed point arithmetics that allows precise financial calculations. Unfortunately, Java&#8217;s BigDecimal class has a rather unwieldy API which is a pain to use. No problem, you may think, because Scala offers a wrapper for BigDecimal that lets you use it like a normal number. That is true, but try this out:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> b<span style="color: #000080;">:</span> BigDecimal <span style="color: #000080;">=</span> <span style="color: #F78811;">0.1</span>
b<span style="color: #000080;">:</span> BigDecimal <span style="color: #000080;">=</span>
  <span style="color: #F78811;">0.1000000000000000055511151231257827021181583404541015625</span></pre></td></tr></table></div>

<p>Oops again. This doesn&#8217;t look much better. What is more, the BigDecimal wrapper class in Scala has abstracted away the control over rounding behaviour and precision offered by the Java API. Of course, you could follow another approach and use Long values to represent money and scale them to the required precision, say one ten thousands of a Dollar. However, there are a number of problems with this approach. First, the value range is limited by MAX_LONG/scale. Second, you have to do complex formatting every time you print the values. Third, you have to code rounding manually because remainders are discarded in integer arithmetics:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> 59L / 10L
res2<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Long</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">5</span></pre></td></tr></table></div>

<p>With this in mind, I have created a Scala currency type that offers arbitrary precision fixed point arithmetics with an easy-to-use API. It is based on the Java&#8217;s BigDecimal type - why reinvent the wheel? Let&#8217;s repeat the first arithmetic operation using the currency type:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> Currency<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1.2</span><span style="color: #F78811;">&#41;</span> - Currency<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1.0</span><span style="color: #F78811;">&#41;</span>
res3<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">0.20</span></pre></td></tr></table></div>

<p>This time the result is correct. It is correct, because the currency type automatically takes care of rounding. By default, the result is rounded to the second decimal place using the ROUND_HALF_UP rounding mode, which means that 1.555 is rounded to 1.56 and -1.555 is rounded to -1.56. Unlike the rounding for Float and Double values, the rounding is symmetric, which is standard in most financial calculations. If you need a different rounding behaviour – no problem. With the currency type, you have complete control over precision and rounding behaviour.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> c <span style="color: #000080;">=</span> Currency<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;1234.56789&quot;</span>, <span style="color: #F78811;">4</span><span style="color: #F78811;">&#41;</span>
c<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">1234.5679</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> d <span style="color: #000080;">=</span> Currency<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">0.1</span>, <span style="color: #F78811;">20</span><span style="color: #F78811;">&#41;</span>
d<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">0.10000000000000000000</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">import</span> Currency.<span style="color: #000000;">RoundingMode</span>.<span style="color: #000080;">_</span>
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> e <span style="color: #000080;">=</span> Currency<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">22.78</span>, <span style="color: #F78811;">2</span>, ROUND<span style="color: #000080;">_</span>DOWN<span style="color: #F78811;">&#41;</span>
e<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">22.78</span></pre></td></tr></table></div>

<p>The first expression creates a currency value with a precision of 1/10000 (= four places right of the decimal point) from a string argument where the fifth decimal place is rounded up in construction. The second expression creates a value of 0.1 (10 cents) with a precision of 10<sup>-20</sup> or 20 places after the decimal point. The third expression constructs a value of 22.78 with a special rounding mode that stipulates that values should always be rounded down. The effect can be seen when performing an arithmetic operation:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> e <span style="color: #000080;">*</span> <span style="color: #F78811;">1.1</span>
res4<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">25.05</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> f <span style="color: #000080;">=</span> Currency<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">22.78</span>, <span style="color: #F78811;">2</span>, ROUND<span style="color: #000080;">_</span>UP<span style="color: #F78811;">&#41;</span>
f<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">22.78</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> e <span style="color: #000080;">==</span> f
res5<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">true</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> f <span style="color: #000080;">*</span> <span style="color: #F78811;">1.1</span>
res6<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">25.06</span></pre></td></tr></table></div>

<p>In this example, the first operation e * 1.1 yields 25.05. We create another currency object with the same value, however with a different rounding mode. When performing the same operation on the second value f, the result differs by one cent from the first because it was rounded differently. This means that arithmetic operations with currency values that have different precision and/or rounding modes are not transitive. This is of course intended behaviour.</p>
<p>The above examples show simple calculations with non-specific currency values. In addition to the numeric amount, the currency type optionally takes a currency designation in the form of an ISO 4217 three-letter code. For example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> salary <span style="color: #000080;">=</span> Currency<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">4789.90</span>, <span style="color: #6666FF;">&quot;USD&quot;</span><span style="color: #F78811;">&#41;</span>
salary<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">4789.90</span> USD
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> bonus <span style="color: #000080;">=</span> Currency<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">500</span>, <span style="color: #6666FF;">&quot;USD&quot;</span><span style="color: #F78811;">&#41;</span>
bonus<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">500.00</span> USD
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> holidayInEurope <span style="color: #000080;">=</span> Currency<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">2400</span>, <span style="color: #6666FF;">&quot;EUR&quot;</span><span style="color: #F78811;">&#41;</span>
holidayInEurope<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">2400.00</span> EUR
&nbsp;
scala<span style="color: #000080;">&gt;</span> salary + bonus
res7<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">5289.90</span> USD
&nbsp;
scala<span style="color: #000080;">&gt;</span> salary + holidayInEurope
MismatchedCurrencyException</pre></td></tr></table></div>

<p>You can add, subtract and compare amounts in the same currency (or of a non-specific currency value), but when you try to add two different currency values, you get an exception. Alternatively, different currencies could be implemented as different subtypes, as suggested in <em>Ch.20, Programming in Scala (Odersky, Spoon, Venners)</em>. This has the advantage that currency mismatches can be detected at compile time. However, it complicates the design and makes mapping the currency type to a database rather awkward. I think that the disadvantages outweigh the benefits, so I implemented the currency type as a “monolithic” class that knows about all currencies. With this design, it becomes easy to format currency values for output.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> salary.<span style="color: #000000;">format</span>
res8<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span> $<span style="color: #F78811;">4</span>,<span style="color: #F78811;">789.90</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">import</span> java.<span style="color: #000000;">util</span>.<span style="color: #000000;">Locale</span>
scala<span style="color: #000080;">&gt;</span> holidayInEurope.<span style="color: #000000;">format</span><span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">new</span> Locale<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;de&quot;</span>, <span style="color: #6666FF;">&quot;DE&quot;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
res9<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span> <span style="color: #F78811;">2.400</span>,00 €
&nbsp;
scala<span style="color: #000080;">&gt;</span> holidayInEurope.<span style="color: #000000;">format</span><span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">new</span> Locale<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;fr&quot;</span>, <span style="color: #6666FF;">&quot;CH&quot;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
res10<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span> € <span style="color: #F78811;">2</span><span style="color: #6666FF;">'400.00
&nbsp;
scala&gt; salary.format(&quot;<span style="color: #0000ff; font-weight: bold;">\u</span>00A4 #,##0.0000&quot;)
res11: String = $ 4,789.9000</span></pre></td></tr></table></div>

<p>The currency class offers a severalfold overloaded <em>format</em> method that formats currency amounts according to either the default locale or a chosen locale. Alternatively, you can specify a formatting pattern and/or symbols to use, or you can use Java&#8217;s DecimalFormat class for formatting. Thus you have total control over the formatted output. The currency class can also verbalise amounts in four languages.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> salary.<span style="color: #000000;">say</span>
res12<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span>
  four thousand seven hundred eighty nine Dollars ninety Cents
&nbsp;
scala<span style="color: #000080;">&gt;</span> salary.<span style="color: #000000;">sayNumber</span>
res13<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span>
  four thousand seven hundred eighty nine <span style="color: #F78811;">90</span>/<span style="color: #F78811;">100</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> pesos <span style="color: #000080;">=</span> Currency<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;1538.20&quot;</span>, <span style="color: #6666FF;">&quot;MXN&quot;</span><span style="color: #F78811;">&#41;</span>
pesos<span style="color: #000080;">:</span> Currency <span style="color: #000080;">=</span> <span style="color: #F78811;">1538.20</span> MXN
&nbsp;
scala<span style="color: #000080;">&gt;</span> pesos.<span style="color: #000000;">say</span><span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">new</span> Locale<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;es&quot;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
res14<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span>
  mil cincocientos treinta y ocho Mexican Peso veinte Centavo
&nbsp;
scala<span style="color: #000080;">&gt;</span> pesos.<span style="color: #000000;">sayNumber</span><span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">new</span> Locale<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;es&quot;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
res15<span style="color: #000080;">:</span> String <span style="color: #000080;">=</span> mil cincocientos treinta y ocho <span style="color: #F78811;">20</span>/<span style="color: #F78811;">100</span></pre></td></tr></table></div>

<p>Finally, the currency class provides a number of convenience methods, such as percentage(), setDecimals(), abs(), fraction(), integral(), pow(), symbol(), getAllCurrencies(), etc., and a number of factory methods and conversion methods to simplify programming with currency values.</p>
<p><a href="http://www.thomasknierim.com/code/Currency.scala" title="Currency.scala">View Source Code</a>.<br />
<a href="http://www.thomasknierim.com/code/currency.zip" title="Download Scala Currency Class">Download source code and API documentation</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomasknierim.com/114/scala/scala-currency-class/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Laments of a would-be Ubuntuist</title>
		<link>http://www.thomasknierim.com/113/open-source/laments-of-a-would-be-ubuntuist/</link>
		<comments>http://www.thomasknierim.com/113/open-source/laments-of-a-would-be-ubuntuist/#comments</comments>
		<pubDate>Fri, 01 May 2009 03:21:26 +0000</pubDate>
		<dc:creator>thomas</dc:creator>
		
		<category><![CDATA[Open Source]]></category>

		<guid isPermaLink="false">http://www.thomasknierim.com/113/open-source/laments-of-a-would-be-ubuntuist/</guid>
		<description><![CDATA[I have been a Linux fan for more than a decade. I used Linux in my own company and projects since 1996  and I was also one of the founding members of the Bangkok Linux User Group. Oddly however, the computer on my desktop still runs on Windows. It&#8217;s a glaring contradiction. I&#8217;ve wanted to [...]]]></description>
			<content:encoded><![CDATA[<p>I have been a Linux fan for more than a decade. I used Linux in my own company and projects since 1996  and I was also one of the founding members of the Bangkok Linux User Group. Oddly however, the computer on my desktop still runs on Windows. It&#8217;s a glaring contradiction. I&#8217;ve wanted to replace Windows for years. There&#8217;s always been a reason not to, mainly because I need to test software under Windows for my customers. Last weekend, the XP installation on my laptop &#8220;forgot&#8221; my user account and with it all account data. Simultaneously, the file system started to behave funny. &#8220;Ah, a sign from above,&#8221; I thought. &#8220;Finally the day has come, I will install Ubuntu on my laptop.&#8221; So I did. Ubuntu Dekstop 9.04 was installed with ease and -even more impressively- it recognised all of my Thinkpad hardware. Even the Wifi connection was up and running without fiddling about.</p>
<p>I should have said &#8220;almost all&#8221; hardware. Unfortunately one piece of hardware refused cooperation with Linux, namely my Novatel USB modem. Since I&#8217;ve come to rely on 3G mobile Internet, this is a knockout criterion. No modem, no Internet. After hours of scouring the Web for possible solutions and  trying out various settings, I gave up in frustration. There wasn&#8217;t anything I could do except zapping the Linux partition and installing old friend XP. To attenuate my disappointment, I will make it a dual boot machine, though. Note to hardware vendors: please take Linux seriously and provide drivers for your nifty electronics. That would make life much easier. I guess I have to postpone my switch-over to Linux for another year. Hopefully I will be able to resist the urge to buy another piece of exotic hardware in the meantime.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomasknierim.com/113/open-source/laments-of-a-would-be-ubuntuist/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Oracle buys Sun</title>
		<link>http://www.thomasknierim.com/112/management/oracle-buys-sun/</link>
		<comments>http://www.thomasknierim.com/112/management/oracle-buys-sun/#comments</comments>
		<pubDate>Tue, 21 Apr 2009 03:51:14 +0000</pubDate>
		<dc:creator>thomas</dc:creator>
		
		<category><![CDATA[IT Management]]></category>

		<category><![CDATA[Tech Trends]]></category>

		<guid isPermaLink="false">http://www.thomasknierim.com/112/management/oracle-buys-sun/</guid>
		<description><![CDATA[Generally I don&#8217;t comment on events in the business world, since this blog is about web development and software engineering. However, the acquisition of Sun by Oracle, which was officially announced yesterday, is so large-scale that it is likely to affect the engineering halls in many subtle ways. Quick facts: the deal is $ 7.4 [...]]]></description>
			<content:encoded><![CDATA[<p>Generally I don&#8217;t comment on events in the business world, since this blog is about web development and software engineering. However, the acquisition of Sun by Oracle, which was officially announced yesterday, is so large-scale that it is likely to affect the engineering halls in many subtle ways. Quick facts: the deal is $ 7.4 billion worth, it was unanimously approved by Sun&#8217;s board and it will be closed this summer. <a href="http://www.sun.com/third-party/global/oracle/index.jsp" title="Sun's Press Statement">Sun</a> and <a href="http://www.oracle.com/us/corporate/press/018363" title="Oracle's Press Statement">Oracle</a> published identical press statements yesterday which sing the praises of the acquisition.</p>
<p>I am not sure whether this is good news. While it was apparent to most observers that Sun was past its zenith, one wonders what will happen to its employees and its innovations. Granted, an acquisition by IBM would have tipped the scales even more in favour of Big Blue&#8217;s dominance in the enterprise market and that might have distorted competition. But one may doubt that Oracle will uphold Sun&#8217;s commitment to the open source community. Sun&#8217;s market was driven by innovation and open source products. Oracle&#8217;s market is clearly not.</p>
<p>In particular, one wonders what will happen to MySQL which was bought by Sun earlier last year and which competes with Oracle&#8217;s core products. Pessimistic observers have already called it MyToast. Will Larry Ellison allow MySQL to compete in the enterprise market? Probably not. Other items in Sun&#8217;s portfolio once considered crown jewels, such Solaris and Glassfish, might also be on the endangered list. But that is pure speculation at this moment. Whether this acquisition will turn out to be a good move for Oracle is currently debated by the industry experts. Whether it is a positive turn for open source community may be reasonably doubted. Time will show.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomasknierim.com/112/management/oracle-buys-sun/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Scala Hits Top 30</title>
		<link>http://www.thomasknierim.com/111/scala/scala-hits-top-30/</link>
		<comments>http://www.thomasknierim.com/111/scala/scala-hits-top-30/#comments</comments>
		<pubDate>Thu, 16 Apr 2009 05:41:04 +0000</pubDate>
		<dc:creator>thomas</dc:creator>
		
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.thomasknierim.com/111/scala/scala-hits-top-30/</guid>
		<description><![CDATA[The Scala programming language has for the first time hit the top 30 of the TIOBE index in April this year. The TIOBE index measures the popularity of programming languages by counting searches for the respective programming language in the most popular search engines. In April 2009, Scala searches were tracked at 0.237% of all [...]]]></description>
			<content:encoded><![CDATA[<p style="margin-bottom: 0in">The Scala programming language has for the first time hit the top 30 of the <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html" target="_blank">TIOBE index</a> in April this year. The TIOBE index measures the popularity of programming languages by counting searches for the respective programming language in the most popular search engines. In April 2009, Scala searches were tracked at 0.237% of all searches which places it at rank 28. This means it is already ahead of other functional languages such as Haskell, Erlang amd Caml. The TIOBE track record is an indicator of Scala&#8217;s growing popularity. Scala entered the TIOBE index in early 2008 and appeared in the Top 50 for the first time in the fourth quarter of 2008.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomasknierim.com/111/scala/scala-hits-top-30/feed/</wfw:commentRss>
		</item>
		<item>
		<title>My Journey Through the World of Programming Languages</title>
		<link>http://www.thomasknierim.com/109/software-engineering/programming-languages/</link>
		<comments>http://www.thomasknierim.com/109/software-engineering/programming-languages/#comments</comments>
		<pubDate>Tue, 07 Apr 2009 02:58:21 +0000</pubDate>
		<dc:creator>thomas</dc:creator>
		
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://www.thomasknierim.com/109/software-engineering/programming-languages/</guid>
		<description><![CDATA[My journey through the world of programming languages began in 1987 with the blinking cursor on a black-and-white computer screen of an Atari ST 1040 computer. After a few hours of playing with the GFA BASIC interpreter, I was hooked. The graphical capabilities of the Atari computer made it possible to program Mandelbrot fractals, the [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.thomasknierim.com/wp-content/uploads/2009/04/lambda_paper.jpg" alt="Photo by Phil Jackson" title="Photo by Phil Jackson" />My journey through the world of programming languages began in 1987 with the blinking cursor on a black-and-white computer screen of an Atari ST 1040 computer. After a few hours of playing with the GFA BASIC interpreter, I was hooked. The graphical capabilities of the Atari computer made it possible to program Mandelbrot fractals, the Towers of Hanoi, the Breakout game, and all those things which newbie programmers like to entertain themselves with. Quite a few of these programs looked peculiarly similar to what people programmed ten years later when the first Java applets appeared. But I am getting ahead of myself. Back in 1987, BASIC was the beginner language. The GFA BASIC dialect was considered quite modern at the time, since it didn&#8217;t have line numbers and it was a full featured procedural language, at least in principle. Yet, it was still a toy. After about six months I felt like writing more ambitious projects and I realised that I had outgrown BASIC. Someone gave me a copy of a C-compiler, so I started learning the C-language. This was a good decision as it turned out later, because I was able to use C throughout the first five years of my career. I found Kernighan-Ritchie style C to be conceptually very close to the GFA BASIC I had started with except for pointers, which were completely new.</p>
<p>The study of C led me to Unix. I began writing clones of Unix tools and utilities for my own use. This was the late 80s before the GNU and Linux phenomena appeared. One such project was a text editor that I enhanced with optimised scrolling routines in 386 Assembler language. I wrote the editor after I had exchanged my Atari computer for a PC. After a few months I had a number of common Unix tools and a nice text editor at my disposal which I could use under MS-DOS. Then I read Andrew Tanenbaum&#8217;s Minix book and I got into system programming. I wrote a micro-kernel task scheduler for the 386 in Assembler. Multi-tasking was a fascinating thing that seemed to be out of reach for an average personal computer. At the time, I briefly considered expanding the micro-kernel into a more complete OS by adding memory management and file management. However, I soon realised the immensity of this task. I had just started studying informatics, and I figured that I wouldn&#8217;t be able to accomplish it while still visiting lectures and doing homework. At university, we were taught Pascal as a “first” programming language and Lisp as a second. Pascal was very easy, of course; it seemed like a verbose dialect of C. - Lisp, on the other hand, I found quite repulsive. - I could appreciate the underlying mathematical idea, the lambda calculus, but the syntax was just awful. I believe it was  IEEE Scheme. The language seemed great for graph-theoretical problems, but unsuitable to express common algorithms in a natural way. In other words, I found it to be a language for eggheads.</p>
<p>At the time, the imperative programming paradigm was predominant. It seemed the best way to get things done, as development tools and libraries for imperative procedural languages were readily available. The next language I learned at the university was Modula 2. I thought of it as an elaboration of Pascal with emphasis on data abstraction and encapsulation. From Modula 2 I learned the importance of encapsulation. Although I didn&#8217;t use Modula 2 for practical applications, I was able to apply the conceptual foundation in my work that revolved around C  programming. After university, I worked in systems programming. I designed and implemented drivers for a company that manufactured proprietary hardware. Then I changed to work with another company in the field of machine translation and computer based training. After 5 years of coding in C, I thought it was time for a change. This was the early nineties, so I turned my attention to application programming with RAD tools which had just hit the market. I learned SQL inside out and created data-driven programs. Visual Basic 3.0 was the killer application in 1993, as it made the construction of Windows GUIs extremely easy. I was able to tie in with my prior Basic experience. Customers liked the productivity that comes with RAD. After about a year, I dropped VB in favour of Delphi, which was superior for this purpose. Likewise, I could tie in with my previous Pascal experience. I learned the rudiments of object oriented programming with Object Pascal, which is odd given that C++ would have been the more natural path to object orientation after having programmed in C for many years. However, Object Pascal taught me proper componentisation.</p>
<p>This was the mid-nineties and a lot of amazing things happened in the IT industry. The most important change was the commercial breakthrough of the Internet. Almost simultaneously, the Linux phenomenon happened. The IT industry boomed and technological progress was fast-paced. The Internet connected everybody everywhere and Linux brought corporate computing horsepower to the desktop. As a result of these changes, I began coding HTML in 1996 and I learned JavaScript and Perl in 1997. The next year brought even more changes, as I decided to gear my business towards web development. Perl seemed like an idiosyncratic Unix solution born out of necessity. It was certainly practical for server side programming, but it was also rather painful and hackish. Fortunately, PHP appeared at around the same time and it offered a much cleaner solution for server programming. Soon I found myself programming web applications in PHP most of the time. LAMP-based applications literally exploded on the Internet between 1998 and 2003. During this period, I also learned the rudiments of Java, C++, and C#. I was responsible for the management of projects implemented in all of these languages. Object-oriented programming had become the mainstream paradigm in the late nineties. I decided that I needed to take on one of these languages more seriously. The obvious choice was Java, since it was general purpose, but still very strong in the field of web development.</p>
<p>So I fully immersed myself in Java when the language made the transition from 1.4 to 1.5. At that point, Java was already mature and mainstream. As a latecomer to Java, the platform seemed huge to me, certainly larger than anything I had looked at before, including .NET. The sheer number of APIs was just unbelievable. It required a sustained effort of two years during which I read a shelf of Java books and began moving from trivial programming exercises to small projects and then to larger projects. Since the mid-2000s, Java has become my mainstay. There are two reasons why I like Java. First, there is a fantastic eco-system connected to the platform. It ranges from best-of-breed IDEs, VMs, and app-servers to a gazillion libraries and frameworks, and (almost) everything is free. Second, Java is extremely scalable and robust. It is not the purest object-oriented language, neither the richest, but Java is probably the one language that transforms average programmers into software engineers. I argue that this is so, because of the high level of standardisation and best practices endorsement in the Java community. I know that there are quite a few people who debate that. However, there&#8217;s a reason why universities teach Java to freshmen and why corporations use Java for enterprise development. It offers the largest and possibly the most robust platform for developing industrial-strength software.</p>
<p>Of course, not everything is hunky-dory in the Java department. I perceive that the main problem is the language itself. - It&#8217;s aging. - Although (or perhaps because) it forces programmers to write tidy code and relinquish dirty C tricks, it tends to be tedious, as it involves generous amounts of boilerplate code. It also lacks good paradigms for fine-grained concurrency control. Fortunately, with the Scala language I discovered a possible solution for these problems. At this point -early 2009- I haven&#8217;t yet done any larger projects in Scala, but my eagerness to do so is growing. Adding the functional paradigm to my programming instruments is very beneficial. It even flows over into my Java work, since it has changed the way I phrase algorithms in Java. The only negative effect is that by learning Scala, the limitations of the Java language became more evident and thus more painful. While functional programming will probably grow in the near future, Java has such a strong position that it won&#8217;t just fade away. Many large systems have been created in Java, so there will be maintenance work for decades to come. Meanwhile, it will be interesting to see how fast the industry embraces functional programming.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomasknierim.com/109/software-engineering/programming-languages/feed/</wfw:commentRss>
		</item>
		<item>
		<title>JSF - Productivity vs. Scalability</title>
		<link>http://www.thomasknierim.com/108/web-development/jsf-scalability/</link>
		<comments>http://www.thomasknierim.com/108/web-development/jsf-scalability/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 08:31:55 +0000</pubDate>
		<dc:creator>thomas</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.thomasknierim.com/108/web-development/jsf-scalability/</guid>
		<description><![CDATA[In my everlasting quest to find the perfect web framework (it&#8217;s futile, I know!) I spent a few more weekends, this time with Java Server Faces. I first got acquainted with JSF two years ago when I played around with Java Studio Creator and I remember being quite impressed by it. I even used it [...]]]></description>
			<content:encoded><![CDATA[<p>In my everlasting quest to find the perfect web framework (it&#8217;s futile, I know!) I spent a few more weekends, this time with Java Server Faces. I first got acquainted with JSF two years ago when I played around with Java Studio Creator and I remember being quite impressed by it. I even used it in a small project, which taught me a lot about the practical side of JSF. However, I did not get a deeper understanding until recently when I read <em>Java Server Faces in Action</em> by Kito D. Mann and <em>Core Java Server Faces</em> by David Geary and Cay Horstmann, both excellent books by the way.</p>
<p>I like RAD tools ever since I worked with Delphi more than a decade ago. In many ways, Delphi was the perfect solution for creating Windows GUI applications. It allowed me to create high-performance apps with great ease and tremendous productivity. When I first came across JSF, I realised it holds a similar promise for the field of web development. In my view, RAD is the most attractive way to create applications. It many not be the best choice for every type of application, but I am sure it is the best choice for a large percentage of run-of-the-mill commercial apps.</p>
<p>The UI-centred approach of RAD tools makes prototyping very easy and it gives development projects a certain “users first” bent which I always found useful in project management. When communicating with customers, a quick mock up screen always beats a bunch of UML diagrams. In addition, I  like the idea of high-level encapsulation offered by the visual component concept that RAD tools are known for. This high-level encapsulation, if properly implemented, should be able to be extended  to non-visual components, so that business logic might benefit from the same mechanism. Of course, in Java all you need are Java Beans (POJOs) for this purpose.</p>
<p>JFS is the attempt to apply a GUI-like component model to web applications. It has an extensible set of visual components, such as text boxes, list boxes, tabs, AJAX widgets, and data-aware widgets. Strictly speaking, the widgets themselves sit on top of JSF. JSF defines the component architecture and an application framework that includes things such as validators, converters, events, listeners and navigation rules. Like GUI widgets, JSF widgets are stateful. The JSF architecture makes this completely transparent to the application. This means, the application is oblivious of the stateless HTTP protocol, or whatever other protocol might be used. It doesn&#8217;t need to take care of preserving and/or restoring state. Sounds a bit like magic, doesn&#8217;t it?</p>
<p>If you look into the internals of JFS, however, it becomes clear that this magic is created at a heavy cost. The first thing to look at is the 6-phase JSF request lifecycle:</p>
<ol>
<li>Restore View</li>
<li>Apply Request Values</li>
<li>Process Validations</li>
<li>Update Model Values</li>
<li>Invoke Application</li>
<li>Render Response</li>
</ol>
<p>Most of these phases do event processing. Quite a bit of additional processing compared to an average web app. But that is not the problem. The problem is in the first phase called “restore view”. This implies that the server maintains an internal representation of the view. When the view is restored, JSF creates a component tree in memory that represents the client view. If you think, this might be a bit memory-intensive, you are probably right. Unfortunately, JSF doesn&#8217;t stop there. Component state is typically stored in what is called managed beans. A managed bean is merely an conceptual extension of a JSP backing bean. “Managed” means that the bean is declared in an XML file and that it is allocated automatically when needed by the JSF framework. However, it is not automatically deallocated, unless it is in page or request scope.</p>
<p>Sounds like a memory eater? To me it does. Since managed beans are typically allocated in session scope, I imagine that a single client can quickly gobble up a few hundred kilobytes or more on the server. Of course you need session scope data in any web app. In this regard, JSF isn&#8217;t different from other web apps. However, with dozens of beans floating around in session memory and new ones being added without direct application intervention, I&#8217;d argue that the programmer loses fine-grained control over memory requirements. I can&#8217;t help asking: does JSF scale? Many people think it doesn&#8217;t. One might even ask further, whether replicating client state on the server is scalable at all. Is it the right approach?</p>
<p>I can&#8217;t answer that question, but I&#8217;ll think twice about using JSF in future projects. Probably one doesn&#8217;t need to be concerned about applications that don&#8217;t go beyond the departmental level with a few dozen concurrent users. But what about a few hundred or a few thousand concurrent users? Even if you create an application for small scale use, it&#8217;s not an attractive choice to use a non-scalable architecture. Who knows how the application will eventually evolve and who will use it? As things stand now, JSF seems like a trade-off to me. You get RAD productivity at the expense of scalability. Or isn&#8217;t this the case? I think the burden of proof is with the JSF camp.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomasknierim.com/108/web-development/jsf-scalability/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Naming Conventions (2)</title>
		<link>http://www.thomasknierim.com/107/software-engineering/naming-conventions-2/</link>
		<comments>http://www.thomasknierim.com/107/software-engineering/naming-conventions-2/#comments</comments>
		<pubDate>Sat, 21 Feb 2009 07:25:29 +0000</pubDate>
		<dc:creator>thomas</dc:creator>
		
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://www.thomasknierim.com/107/software-engineering/naming-conventions-2/</guid>
		<description><![CDATA[Language conventions are often omitted from formal programming conventions, which is a bit odd considering their importance. The most obvious language convention is the selection of the language itself. This point is so obvious, that it&#8217;s often missed. Mind you, not every programmer is fluent in English. Just a fraction are native English speakers. Hence, [...]]]></description>
			<content:encoded><![CDATA[<p>Language conventions are often omitted from formal programming conventions, which is a bit odd considering their importance. The most obvious language convention is the selection of the language itself. This point is so obvious, that it&#8217;s often missed. Mind you, not every programmer is fluent in English. Just a fraction are native English speakers. Hence, English should be chosen only if all members of the development team are comfortable with it. Otherwise, it is more appropriate to choose the native language of the developer team. If the developer team is international, English is likely to be used as the common basis. If the conventions prescribe English and if some team members are less fluent in English, identifier names must be treated with special care. I recently came across a piece of software developed in Germany where identifier names for an organisational structure where assigned as follows:</p>
<table>
<tr>
<th>German Term</th>
<th>What it means</th>
<th>Identifier Name Used</th>
</tr>
<tr>
<td>Organisationseinheit</td>
<td>organisational unit</td>
<td>department</td>
</tr>
<tr>
<td>Unternehmen</td>
<td>branch/sector</td>
<td>division</td>
</tr>
<tr>
<td>Unternehmensbereich</td>
<td>division</td>
<td>divisionArea</td>
</tr>
<tr>
<td>Abteilung</td>
<td>department</td>
<td>section</td>
</tr>
</table>
<p>The meaning of these identifiers doesn&#8217;t quite correspond to what an English speaker would expect them to mean, which is rather confusing. Yet, if you look up these terms in a dictionary, you find that all of them, with exception of divisionArea, are valid translations of the original German term. This is one example where it would have been better to use German identifiers instead. These terms appeared in source code that had English identifiers and German JavaDoc comments. Perhaps as a rule of thumb, it&#8217;s better not to use English identifiers if the team is not comfortable with English documentation as well. Again, in an international environment this may not be an option. Therefore, it might be worthwhile to have an English speaker refactor code written by non-native speakers for the sake of clarity.</p>
<p>Another aspect that pertains to language conventions is grammar. You might think that I am nitpicking when mentioning grammar in computer programs. The point is that proper grammar facilitates understanding. This is true for natural language as well as program code. The grammatical rules for identifier names are few and simple. Use nouns for class names and object references, because classes and objects abstract real world objects. In some cases, objects directly correspond to entities of the problem domain, such as <em>Customer</em>, <em>Order</em>, <em>Department</em>, <em>User</em>, etc. In other cases they do not. It is important to qualify class names further if a single noun does not describe it sufficiently. Examples of qualified nouns are <em>TransferredFunds</em>, <em>AppraisalStatistics</em>, <em>AvailableOptions</em>. Use verbs for methods and functions, because methods abstract behaviour. Good examples for method names are <em>addTax()</em>, <em>computeCRC()</em>, <em>checkAvailability()</em>, <em>getDepartment()</em>. Avoid using nouns as method identifiers, such as <em>department()</em> instead of <em>getDepartment()</em> or adjectives such as <em>available()</em> instead of <em>getAvailability()</em>. An exception to this rule would be languages where methods directly represent properties, because property names should be either adjectives or nouns. Likewise, interfaces should be nouns, or in some special cases adjectives, such as <em>Triangular</em>, <em>Centred</em>, <em>Deductible</em>, etc. depending on their purpose. In the latter case, the adjective is derived from the verb deduct and by convention the interface defines a method with the same name, i.e. <em>deduct()</em>. Other examples for similarly named interfaces are <em>Readable</em>, <em>Comparable</em>, or <em>Sortable</em>. Finally, we have identifiers for local variables, parameters, and fields. What should these look like? There are no hard rules for these program elements, since local variables, parameters and fields can represent anything from objects to properties, primitives, and even methods. It&#8217;s best if grammar conventions follow those of the type the identifier refers to.</p>
<p>Next I want to talk about identifier naming schemes. These are fixed sets of conventions for assigning names. Two widely used schemes are positional notation and Hungarian notation. Positional notation is typically used in legacy languages where identifier names are very short, as for example in older Fortran and Cobol programs. Another example is the 8.3 notation of MS-DOS file system. Identifiers that use positional notation are usually unintelligible without a key. An example would be <em>APRPOCTT</em>, where the first two characters <em>AP </em>stand for the main program module “Accounts Payable”, <em>RP </em>stands for the sub-module “reporting” and <em>OCT1 </em>means “operating costs total 1”. Needless to say that this notation defies easy readability and should not be used unless absolutely necessary. A more widely used scheme is Hungarian notation. Hungarian notation is characterised by prefixes, and sometimes postfixes, which are added to the variable name and which carry type information. For example, in the original Hungarian notation suggested by Charles Simonyi for the C language, <em>b</em> stands for boolean, <em>i</em> for integer, <em>p</em> for pointer, <em>sz</em> for zero-terminated strings, and so on. These prefixes can be combined. The name <em>arrpszMessages</em>, for example, refers to an array of pointers to zero-terminated strings. Sometimes Hungarian notation is applied to conceptual types rather than implementation types. For instance, the identifier <em>arrstrMessages</em> refers to an array of strings without saying anything about pointers or zero-termination.</p>
<p>Hungarian notation is still used today with certain languages, such as C, C++ and Delphi. In C++ the following prefixes are often used to denote scope: <em>g_</em> for global, <em>m_</em> for class members (fields), <em>s_</em> for static members, and <em>_</em> for local variables. Delphi is unusual in the sense that Hungarian notation denote object types. The type names themselves are always prefixed with the letter <em>T</em> in Delphi, so a button class would be defined as TButton and an instance of that type would be prefixed with <em>Btn</em> or something similar, such as <em>BtnOK</em>, <em>BtnCancel</em>, <em>BtnRetry</em>, etc. There is a lot of debate whether Hungarian notation is generally useful or not. The main criticism is that implementation types are somewhat irrelevant for the programmer writing code in a statically typed language, since types are checked by the compiler. When the programmer needs to know about the type of a variable or an object, modern IDEs can usually resolve it automatically. In this case, the prefixes just add unnecessary visual clutter. Hungarian notation still has its place in C, but it&#8217;s definitely not that useful with contemporary languages and development tools. The same can be said in principle about most other identifier naming schemes. Naming schemes generally attempt to add metadata to identifiers, or create artificial namespaces. Most modern languages provide better means to both ends. For example, the Java language has annotations for metadata and packages for namespaces. There is usually no need to employ naming schemes with most modern languages. It&#8217;s probably more worthwhile to spent effort on finding intelligible and descriptive names rather than inventing clever naming schemes.</p>
<p>Next time I will talk about the practical considerations in choosing good identifier names and provide some examples to illustrate best practices.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomasknierim.com/107/software-engineering/naming-conventions-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>CSS Grid Layouts Brittle</title>
		<link>http://www.thomasknierim.com/106/web-development/css-grid-layouts-brittle/</link>
		<comments>http://www.thomasknierim.com/106/web-development/css-grid-layouts-brittle/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 03:19:31 +0000</pubDate>
		<dc:creator>thomas</dc:creator>
		
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://www.thomasknierim.com/106/web-development/css-grid-layouts-brittle/</guid>
		<description><![CDATA[Recently I changed parts of the HTML template for this blog from CSS divs to tables. Gasp, tables? That&#8217;s so nineties. Indeed, it is. However, the CSS floating divs were just too brittle. An occasional wide image or wide block of &#60;pre&#62; text would mess up the sidebar badly. Also, the visual results were different [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I changed parts of the HTML template for this blog from CSS divs to tables. Gasp, tables? That&#8217;s so nineties. Indeed, it is. However, the CSS floating divs were just too brittle. An occasional wide image or wide block of &lt;pre&gt; text would mess up the sidebar badly. Also, the visual results were different in different browsers. The problem puppy was a browser whose name shall not be mentioned (but I can tell you it starts with “I” and ends with “6.0”). Call me old-fashioned, but I think that a table-based design often beats CSS in terms of robustness. Why spend hours testing a complex CSS design if the same job can be accomplished with tables in a few minutes? Tables are especially handy with multiple columns, nested columns and rows, and elastic designs. I would still use CSS in most situations, but you can&#8217;t beat tables for robust grid layouts.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomasknierim.com/106/web-development/css-grid-layouts-brittle/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Naming Conventions (1)</title>
		<link>http://www.thomasknierim.com/105/software-engineering/identifier-naming-1/</link>
		<comments>http://www.thomasknierim.com/105/software-engineering/identifier-naming-1/#comments</comments>
		<pubDate>Sun, 25 Jan 2009 06:13:22 +0000</pubDate>
		<dc:creator>thomas</dc:creator>
		
		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://www.thomasknierim.com/105/software-engineering/identifier-naming-1/</guid>
		<description><![CDATA[Nomen est omen. This old Latin proverb means something like &#8220;the name says it all&#8221;. The ancients were superstitious, and they believed that names carry special powers. Names were thought to predispose its subject to bring about certain fortunes or to have certain qualities. Today, we have largely done away with such superstitions. In the [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Nomen est omen.</strong> This old Latin proverb means something like &#8220;the name says it all&#8221;. The ancients were superstitious, and they believed that names carry special powers. Names were thought to predispose its subject to bring about certain fortunes or to have certain qualities. Today, we have largely done away with such superstitions. In the scientific worldview, names are nothing but symbolic artefacts without intrinsic powers. However, there is one field where this Latin proverb still applies, and where it is indeed more true than ever. Oddly, this field wasn&#8217;t even known to the Romans. I am talking about software development, of course. Names have a special importance to software, or perhaps better, the practice of naming does. The first thing I do when looking at a piece of software written by somebody else is to look at the names given to variables and other program elements. My experience has shown that the quality of the identifier names corresponds directly to the overall quality of the program code.</p>
<p>Identifier names are a crucial part of any program. They provide clues about semantics and program logic. They make or break code readability. They determine whether code is self-documenting or not. So, the old Latin proverb &#8220;nomen est omen&#8221; can be applied as follows: If you read through a piece of code for the first time and you have no idea what the variables are supposed to represent, or what the methods are supposed to accomplish, then this is a bad omen. It suggests that the author was not quite sure how to formulate the problem (or didn&#8217;t care) and it can be expected that the other aspects of the program are at least as confusing. If you read through a piece of code and the identifier names are easily comprehensible and fit together like the pieces of a jigsaw puzzle, then this is a good omen. It suggests that the author had a clear idea of the task at hand. Naturally, there are many intermediate levels between these two opposites.</p>
<p>While contemporary code editors and IDEs are very powerful, identifier naming is one of the things that cannot currently be automated by these tools. It is up to the programmer to choose identifier names. Since good naming practice is essential for code maintainability, we will first define what makes a good naming practice and then look at some concrete examples of good and bad strategies. There are three basic ingredients for a good naming practice: (1) semantic precision, (2) consistency, (3) the right amount of verbosity. The first aspect is by far the hardest to get right. Semantic precision means that the chosen name is appropriate, unambiguous, well defined, and compliant with conventions. Consistency means that names are formed according to common patterns and that terms are used consistently throughout the program. The right amount of verbosity relates to identifier length. It means that names do not leave anything open to guesswork while avoiding redundancy.</p>
<p>An identifier usually consists of a single word or a combination of words. In case of the latter, the individual words are often set apart by using CamelCase or the &#8220;_&#8221; underscore character. One of the most commonly found questionable practice is the use of abbreviations instead of written out words, for example <em>rptCount </em>instead of <em>repeatCount</em>. The word count indicates that this variable is a counter, but what is counted? Repetitions, receptors, recipients, red points, or something else? Reptiles perhaps? By adding a mere three characters and writing out the first word, the ambiguity is eliminated. This doesn&#8217;t mean that abbreviations are always bad. For example, nothing speaks against widely used acronyms like <em>URI </em>for <em>UniqueResourceIdentifier</em>, or <em>LCD </em>instead of <em>LiquidCrystalDisplay</em>. Likewise, domain-specific abbreviations are acceptable, if the program is written within that domain, for example <em>FOB </em>(free on board) in the shipping domain, or <em>VAT </em>(value added tax) in the accounting domain. By definition this also includes acronyms in the software domain, such as <em>i18n </em>for internationalisation, or <em>ftp </em>for file transfer protocol. In addition, there are a number of  pre- and postfixes used ubiquitously in programming, such as <em>min, max, fmt, pos, len, num, cnt,</em> etc. which every programmer understands. Generally speaking, abbreviations and acronyms should be used sparingly and only when they are common and free of ambiguity.</p>
<p>This also means that one-letter or two-letter variable names, such as <em>a, b, c, f1, x2,</em> etc. are generally a bad idea, because they say nothing about the content of the variable. There is one exception to this rule: loop indices. Since loop indices (or iterator variables) are only used to to iterate through a collection of values, they don&#8217;t have any intrinsic meaning. So one might as well give them one-letter names. By convention, the letters <em>i, j, k,</em> etc. are used, whereas the alphabetic order corresponds to the loop nesting level. This mean <em>i</em> is used for the outermost loop, <em>j</em> for the second nested loop, <em>k</em> for the third, and so on. This is standard practice for loop indices, but in other cases, index position corresponds to certain semantics. In this case, indices do have meaning. For example, one might define an array of counters, where <em>counter[0]</em> contains the number of students, <em>counter[1]</em> contains the number of passed tests and <em>counter[2]</em> contains the number of failed tests. Since the index numbers themselves don&#8217;t communicate any meaning, it is appropriate to define an enumerable type or a set of integer constants that conveys this meaning, for example <em>STUDENTS=0</em>, <em>PASSED_TESTS=1</em>, <em>FAILED_TESTS=2</em>, and so on.</p>
<p>This is all pretty much standard programming practice. Next time we will look at common identifier naming schemes, their merits and demerits, as well as language conventions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomasknierim.com/105/software-engineering/identifier-naming-1/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Scala Tutorial (3)</title>
		<link>http://www.thomasknierim.com/104/scala/scala-tutorial-3/</link>
		<comments>http://www.thomasknierim.com/104/scala/scala-tutorial-3/#comments</comments>
		<pubDate>Sat, 27 Dec 2008 06:51:24 +0000</pubDate>
		<dc:creator>thomas</dc:creator>
		
		<category><![CDATA[Scala]]></category>

		<guid isPermaLink="false">http://www.thomasknierim.com/104/scala/scala-tutorial-3/</guid>
		<description><![CDATA[Now that we have covered the somewhat “dry” foundations of the Scala language, let&#8217;s move on to the good stuff. That is to say, let&#8217;s move on to the functional aspects of Scala. Some of these may appear foreign to you if your main language is object-oriented or procedural. They definitely appeared foreign to me [...]]]></description>
			<content:encoded><![CDATA[<p>Now that we have covered the somewhat “dry” foundations of the Scala language, let&#8217;s move on to the good stuff. That is to say, let&#8217;s move on to the functional aspects of Scala. Some of these may appear foreign to you if your main language is object-oriented or procedural. They definitely appeared foreign to me at first. It cannot be stressed enough that functions are primary language constructs in Scala. I mentioned  function literals. Here is an example:</p>

<div class="wp_syntax"><div class="code"><pre class="scala scala" style="font-family:monospace;"><span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> x - <span style="color: #F78811;">1</span></pre></div></div>

<p>A function literal is simply a function without a name. You can assign this expression to an ordinary variable and then use it later to execute the function:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">var</span> decrease <span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> x - <span style="color: #F78811;">1</span>
decrease<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">11</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>You can probably guess what the value of <em>decrease(11)</em> is. Up to this point, this isn&#8217;t very exiting. However, because decrease is a var and not a val, you can reassign it a different function literal later on depending on some condition. Or you could pass it as an argument to another function. You might begin to see the possibilities behind the first class function concept. Instead of the trivial example above you can use this capability with more complex methods. For example, you could use it for callback methods, or for wrapping methods in an API and facilitating common OOP patterns, such as the facade and adapter patterns. All of this can be done, unlike in Java, with a minimum of syntactical fuss.</p>
<p>But it gets even better. Functions in Scala are not limited to use simple parameters as in the above example. For example, you could write something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="scala scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">var</span> decrease <span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">:</span> <span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> x – something</pre></div></div>

<p>Obviously, the variable <em>something</em>, which is subtracted from <em>x</em> is not defined in this expression. The assignment is still syntactically valid. This means the variable decrease is properly defined, but it cannot be applied. In other words, to apply a value or to execute the function meaningfully, it must be executed in a context where <em>something</em> is defined. The above expression is an “open term” and something is called a “free variable”. An open term is the principal ingredient of a closure. Simply put, a closure closes an open term by providing the necessary context. This is an example of a closure:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">something <span style="color: #000080;">=</span> <span style="color: #F78811;">10</span>
decrease<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">100</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>The first line defines the free variable <em>something</em>. The second line therefore produces a meaningful value. That&#8217;s the closure. In terms of computer science, a closure is a function that is evaluated and whose result depend on an outer context. It&#8217;s like an inner class in Java that references variables of its outer class. However, the Scala construct is more powerful and much easier to write. It can be useful in a number of situations where the place where behaviour is defined is removed from the place where the behaviour is applied.</p>
<p>While closures are supported by languages that one wouldn&#8217;t consider functional programming languages, higher-order functions are a hallmark of the functional paradigm. The concept is simple enough. A higher-order function is a function that either takes one or more function parameters or returns a function, or both. The prime example would be the map function. The map function takes an list as input and produces an output list using a specific algorithm. The algorithm is of course represented by another function that is passed as a parameter to the map function. In Java, this would typically require a the use of a for loop or an iterator. In Scala, the mapping can be expressed succinctly with a single line. Here are some examples:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> List<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;alpha&quot;</span>, <span style="color: #6666FF;">&quot;beta&quot;</span>, <span style="color: #6666FF;">&quot;crash&quot;</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">map</span><span style="color: #F78811;">&#40;</span>
  p <span style="color: #000080;">=&gt;</span> p.<span style="color: #000000;">substring</span><span style="color: #F78811;">&#40;</span>0,<span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
res0<span style="color: #000080;">:</span> List<span style="color: #F78811;">&#91;</span>java.<span style="color: #000000;">lang</span>.<span style="color: #000000;">String</span><span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> List<span style="color: #F78811;">&#40;</span>a, b, c<span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> List<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span>, <span style="color: #F78811;">2</span>, <span style="color: #F78811;">3</span><span style="color: #F78811;">&#41;</span> map <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span> <span style="color: #000080;">*</span> <span style="color: #F78811;">2</span><span style="color: #F78811;">&#41;</span>
res1<span style="color: #000080;">:</span> List<span style="color: #F78811;">&#91;</span><span style="color: #9999cc; font-weight: bold;">Int</span><span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> List<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">2</span>, <span style="color: #F78811;">4</span>, <span style="color: #F78811;">6</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> List<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;Tango&quot;</span>, <span style="color: #6666FF;">&quot;Mango&quot;</span>, <span style="color: #6666FF;">&quot;Bobo&quot;</span>, <span style="color: #6666FF;">&quot;Gogo&quot;</span><span style="color: #F78811;">&#41;</span>
    map <span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">endsWith</span><span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;go&quot;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
res2<span style="color: #000080;">:</span> List<span style="color: #F78811;">&#91;</span><span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> List<span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">true</span>, <span style="color: #0000ff; font-weight: bold;">true</span>, <span style="color: #0000ff; font-weight: bold;">false</span>, <span style="color: #0000ff; font-weight: bold;">true</span><span style="color: #F78811;">&#41;</span></pre></td></tr></table></div>

<p>These examples are quite trivial, but they illustrate the basic idea of higher-order functions. The first line maps a list of strings to another list of strings. The result elements retain only the first characters. The second line is produced by the interactive Scala Interpreter; it displays the result of the expression. A function literal is used as the parameter of the map function in line 1. Line 5 and 9 make use of the underscore notation which is a placeholder for the bound variable, which is the list element parameter in this case. Thus <em>(_*2)</em> is equivalent to <em>(i => i * 2)</em>.</p>
<p>Higher-order functions are not just a succinct form of control abstraction. They are also very useful for reducing code duplication and redundancy. The typical use case is abstracting behaviour. There are a number of design patterns for abstracting behaviour which are popular in languages like C++ or Java, such as the strategy pattern. Consider the following Java example:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
</pre></td><td class="code"><pre class="java java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.*</span>;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.*</span>;
&nbsp;
<span style="color: #000000; font-weight: bold;">interface</span> FileNameMatcher <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">boolean</span> matchFileName<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> fileName, <span style="color: #003399;">String</span> query<span style="color: #009900;">&#41;</span>;
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> FileNameMatcherEnding <span style="color: #000000; font-weight: bold;">implements</span> FileNameMatcher <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> matchFileName<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> fileName,
    <span style="color: #003399;">String</span> query<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> fileName.<span style="color: #006633;">endsWith</span><span style="color: #009900;">&#40;</span>query<span style="color: #009900;">&#41;</span>;
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> FileNameMatcherContaining <span style="color: #000000; font-weight: bold;">implements</span> FileNameMatcher <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> matchFileName<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> fileName,
    <span style="color: #003399;">String</span> query<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> fileName.<span style="color: #006633;">contains</span><span style="color: #009900;">&#40;</span>query<span style="color: #009900;">&#41;</span>;
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> FileNameMatcherRegex <span style="color: #000000; font-weight: bold;">implements</span> FileNameMatcher <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> matchFileName<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> fileName,
    <span style="color: #003399;">String</span> query<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> fileName.<span style="color: #006633;">matches</span><span style="color: #009900;">&#40;</span>query<span style="color: #009900;">&#41;</span>;
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FileMatcher <span style="color: #009900;">&#123;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> filesMatching<span style="color: #009900;">&#40;</span>FileNameMatcher
    fileNameMatcher, <span style="color: #003399;">String</span> query<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">File</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> files <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">File</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;.&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">listFiles</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>;
    List<span style="color: #339933;">&lt;</span>string<span style="color: #339933;">&gt;</span> matchResult <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ArrayList<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: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">File</span> thisFile <span style="color: #339933;">:</span> files<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #000000; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>fileNameMatcher.<span style="color: #006633;">matchFileName</span><span style="color: #009900;">&#40;</span>
        thisFile.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, query<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        matchResult.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>thisFile.<span style="color: #006633;">toString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>;
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000000; font-weight: bold;">return</span> matchResult.<span style="color: #006633;">toArray</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>;
  <span style="color: #009900;">&#125;</span>
&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>
    <span style="color: #003399;">String</span> query <span style="color: #339933;">=</span> args<span style="color: #009900;">&#91;</span>0<span style="color: #009900;">&#93;</span>;
    <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> matchingFiles;
    matchingFiles <span style="color: #339933;">=</span> filesMatching<span style="color: #009900;">&#40;</span>
      <span style="color: #000000; font-weight: bold;">new</span> FileNameMatcherEnding<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, query<span style="color: #009900;">&#41;</span>;
    matchingFiles <span style="color: #339933;">=</span> filesMatching<span style="color: #009900;">&#40;</span>
      <span style="color: #000000; font-weight: bold;">new</span> FileNameMatcherContaining<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, query<span style="color: #009900;">&#41;</span>;
    matchingFiles <span style="color: #339933;">=</span> filesMatching<span style="color: #009900;">&#40;</span>
      <span style="color: #000000; font-weight: bold;">new</span> FileNameMatcherRegex<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>, query<span style="color: #009900;">&#41;</span>;
  <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>This is a classic example of the strategy pattern. The core piece of this code is the one-method interface named <em>FileNameMatcher</em>. This interface abstracts different ways to match a file name. The three implementing methods match a file name either by looking whether a file name ends with a given string, whether it contains a given string, or whether it matches a regular expression. The <em>filesMatching()</em> method of the <em>FileMatcher </em>class takes a strategy implementation and applies it to a list that contains all files in the current directory. Finally, the <em>main()</em> function calls the <em>FileMatcher </em>with the three different strategy objects that were defined earlier. All together that&#8217;s 55 lines of Java code. Compare this to the Scala equivalent which appears in the book Programming in Scala by Odersky, Spoon and Venners (page 199):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="scala scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">object</span> FileMatcher <span style="color: #F78811;">&#123;</span>
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">private</span> <span style="color: #0000ff; font-weight: bold;">val</span> filesHere<span style="color: #000080;">=</span><span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">new</span> java.<span style="color: #000000;">io</span>.<span style="color: #000000;">File</span><span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;.&quot;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">listFiles</span>
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">private</span> <span style="color: #0000ff; font-weight: bold;">def</span> filesMatching<span style="color: #F78811;">&#40;</span>matcher<span style="color: #000080;">:</span> String <span style="color: #000080;">=&gt;</span> <span style="color: #9999cc; font-weight: bold;">Boolean</span><span style="color: #F78811;">&#41;</span><span style="color: #000080;">=</span>
    <span style="color: #0000ff; font-weight: bold;">for</span> <span style="color: #F78811;">&#40;</span>file <span style="color: #000080;">&lt;</span>- filesHere; <span style="color: #0000ff; font-weight: bold;">if</span> matcher<span style="color: #F78811;">&#40;</span>file.<span style="color: #000000;">getName</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
      <span style="color: #0000ff; font-weight: bold;">yield</span> file
&nbsp;
  <span style="color: #0000ff; font-weight: bold;">def</span> filesEnding<span style="color: #F78811;">&#40;</span>query<span style="color: #000080;">:</span> String<span style="color: #F78811;">&#41;</span><span style="color: #000080;">=</span>
    filesMatching<span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">endsWith</span><span style="color: #F78811;">&#40;</span>query<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> filesContaining<span style="color: #F78811;">&#40;</span>query<span style="color: #000080;">:</span> String<span style="color: #F78811;">&#41;</span><span style="color: #000080;">=</span>
    filesMatching<span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">contains</span><span style="color: #F78811;">&#40;</span>query<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> filesRegex<span style="color: #F78811;">&#40;</span>query<span style="color: #000080;">:</span> String<span style="color: #F78811;">&#41;</span><span style="color: #000080;">=</span>
    filesMatching<span style="color: #F78811;">&#40;</span><span style="color: #000080;">_</span>.<span style="color: #000000;">matches</span><span style="color: #F78811;">&#40;</span>query<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span>
&nbsp;
<span style="color: #0000ff; font-weight: bold;">object</span> Main <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> main<span style="color: #F78811;">&#40;</span>args<span style="color: #000080;">:</span> Array<span style="color: #F78811;">&#91;</span>String<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">val</span> query <span style="color: #000080;">=</span> args<span style="color: #F78811;">&#40;</span>0<span style="color: #F78811;">&#41;</span>;
    <span style="color: #0000ff; font-weight: bold;">var</span> matchingFiles <span style="color: #000080;">=</span> FileMatcher.<span style="color: #000000;">filesEnding</span><span style="color: #F78811;">&#40;</span>query<span style="color: #F78811;">&#41;</span>
    matchingFiles <span style="color: #000080;">=</span> FileMatcher.<span style="color: #000000;">filesContaining</span><span style="color: #F78811;">&#40;</span>query<span style="color: #F78811;">&#41;</span>
    matchingFiles <span style="color: #000080;">=</span> FileMatcher.<span style="color: #000000;">filesRegex</span><span style="color: #F78811;">&#40;</span>query<span style="color: #F78811;">&#41;</span>
  <span style="color: #F78811;">&#125;</span>
<span style="color: #F78811;">&#125;</span></pre></td></tr></table></div>

<p>Brevity is the soul of wit. Obviously, there is no need to create strategy objects in Scala. With higher-order functions, the strategy pattern simply evaporates. This is one of the areas where  Scala&#8217;s powerful language constructs eliminate the need for patterns. Critical voices have said that design patterns are crutches for weaknesses in certain programming languages. Although I don&#8217;t fully agree with this statement, it seems to hold true in case of the strategy pattern. The above Scala example is actually more verbose than necessary. One could make the <em>filesMatching()</em> method public and call it directly with a function parameter from outside the <em>FileMatcher</em> object. At the cost of full encapsulation, this would make the code three lines shorter.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.thomasknierim.com/104/scala/scala-tutorial-3/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
