<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Object Mentor Blog: Tag Scala</title>
    <link>http://blog.objectmentor.com/articles/tag/scala</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>Scala Bowling Kata - still in the middle I suppose</title>
      <description>I had a 3.5 hour flight today. I realized I was missing some of the validation from the Ruby version related to how many rolls a valid game should allow:
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_scala "&gt;  &amp;quot;One more roll on a game with 20 rolls and an open 10th frame&amp;quot; should {
    20 times { roll(1) }
    roll(1) must throwA[IllegalArgumentException]
  }

  &amp;quot;Two more rolls a game with 10 spares&amp;quot; should {
    10 times { spare }
    roll(1)
    roll(1) must throwA[IllegalArgumentException]
  }

  &amp;quot;Two marks in the 10th frame should&amp;quot; should {
    18 times { roll(1) }
    strike
    spare
    roll(1) must throwA[IllegalArgumentException]
  }&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;On my flight from &lt;span class="caps"&gt;DFW&lt;/span&gt; to &lt;span class="caps"&gt;SNA&lt;/span&gt;, I got these behaviors implemented. The code was pretty ugly!&lt;/p&gt;


	&lt;p&gt;However, ugly code in hand, passing examples, a slight understanding of some of the problems with my code and a desire to make the BowlingScorer immutable was all I needed to make progress.&lt;/p&gt;


I removed the index instance field by rewriting the score method and injecting a tuple into foldLeft (written here using the short-hand notation /:):
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_scala "&gt;  def scoreAt(frame:Int) = 
    ((0,0) /: (1 to frame)) { (t, _) =&amp;gt;  
      (t._1 + scoreAtIndex(t._2), t._2 + incrementAt(t._2))
    }._1&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

I had a mini state machine to track whether the first ball had been thrown yet or not. I replaced that by walking the list of scores:
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;  def onFirstThrow = {
    var index = 0
    while(index &amp;lt; rolls.length)
      if(isStrike(index)) index += 1 else index += 2
    index == rolls.length
  }&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;While I am happy I was able to remove the index variable, which was really a parameter being passed around in a field (ugly), I am not happy with this method.&lt;/p&gt;


I changed the roll method to return a new instance of a BowlingScorer, making the bowling scorer immutable:
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_scala "&gt;  def roll(roll:Int) = {
    validate(roll)
    new BowlingScorer(rolls ++ Array(roll))
  }&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;So I think I&amp;#8217;m still somewhere in the middle of working through this code. Again, I&amp;#8217;m still learning Scala. I have a lot to learn. I really only barely understand functional programming and, frankly, the Eclipse &lt;span class="caps"&gt;IDE&lt;/span&gt;, while functional, is getting in the way quite a bit. So for a toy example it is OK. Given the choice of this environment or vi and the command line, I&amp;#8217;d not pick the former. (I might give the other &lt;span class="caps"&gt;IDE&lt;/span&gt;&amp;#8217;s a go, but that&amp;#8217;s not really what I&amp;#8217;m interested in learning right now.)&lt;/p&gt;


	&lt;p&gt;So here&amp;#8217;s the next version. I plan to work through all of the comments I&amp;#8217;ve yet to process from the previous blog posting over the next few days. If you can recommend a better implementation of onFirstThrow, I&amp;#8217;d appreciate it.&lt;/p&gt;


	&lt;p&gt;Other general comments also welcome.&lt;/p&gt;


	&lt;p&gt;&lt;b&gt;&lt;i&gt;BowlingScorerExampleGroup.scala&lt;/b&gt;&lt;/i&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_scala "&gt;package com.om.example

import org.specs._

object BowlingScorerExampleGroup extends SpecificationWithJUnit {
  var scorer = new BowlingScorer(Nil);

  def roll(value:Int) =
    scorer = scorer.roll(value) 

  def haveAScoreOf(expected:Int) =
    scorer.score must_== expected

  def strike =
    roll(10)

  def spare {
    roll(5)
    roll(5)
  }

  implicit def intToDo(count: Int) = {
    new {
      def times(f: =&amp;gt; Unit) = {
        1 to count foreach { _ =&amp;gt; f }
      }
    }
  }

  &amp;quot;A Newly Created Bowling Scorer&amp;quot; should {
    haveAScoreOf(0)
  }

  &amp;quot;A game with all 0's&amp;quot; should {
    20 times { roll(0) }
    haveAScoreOf(0)
  }

  &amp;quot;A game with all 1's&amp;quot; should {
    20 times { roll(1) }
    haveAScoreOf(20)
  }

  &amp;quot;A game with a single spare followed by a 5&amp;quot; should {
    spare
    roll(5)
    haveAScoreOf(20)
  }

  &amp;quot;A game with all 5's&amp;quot; should {
    10 times { spare }
    roll(5)
    haveAScoreOf(150)
  }

  &amp;quot;A game with a single strike followed by a 4&amp;quot; should {
    strike
    roll(4)
    haveAScoreOf(18)
  }

  &amp;quot;A game with a strike, spare then an open frame with two 3's&amp;quot; should {
    strike
    spare
    2 times { roll(3) }
    haveAScoreOf(39)
  }

  &amp;quot;A game with strike, spare then an open frame with two 3's&amp;quot; should {
    spare
    strike
    2 times { roll(3) }
    haveAScoreOf(42)
  }

  &amp;quot;A Dutch 200 game, Spare-Strike&amp;quot; should {
    5 times {
      spare 
      strike
    }
    spare
    haveAScoreOf(200)
  }

  &amp;quot;A Dutch 200 game, Strike-Spare&amp;quot; should {
    5 times {
      strike
      spare 
    }
    strike
    haveAScoreOf(200)
  } 

  &amp;quot;A Perfect game&amp;quot; should {
    12 times { strike }
    haveAScoreOf(300)
  }

  &amp;quot;The score for each frame of a Perfect game, each frame&amp;quot; should {
    12 times { strike }
    1 to 10 foreach { frame =&amp;gt; scorer.scoreAt(frame) must_== 30 * frame }
  }

  &amp;quot;An individaul roll of &amp;gt; 10&amp;quot; should {
    roll(11) must throwA[IllegalArgumentException]
  }

  &amp;quot;An iniviaul roll of &amp;lt; 0&amp;quot; should {
    roll(-1) must throwA[IllegalArgumentException]
  }

  &amp;quot;A frame trying to contain more than 10 pins&amp;quot; should {
    roll(8)
    roll(3) must throwA[IllegalArgumentException]
  }

  &amp;quot;One more roll on a game with 20 rolls and an open 10th frame&amp;quot; should {
    20 times { roll(1) }
    roll(1) must throwA[IllegalArgumentException]
  }

  &amp;quot;Two more rolls a game with 10 spares&amp;quot; should {
    10 times { spare }
    roll(1)
    roll(1) must throwA[IllegalArgumentException]
  }

  &amp;quot;Two marks in the 10th frame should&amp;quot; should {
    18 times { roll(1) }
    strike
    spare
    roll(1) must throwA[IllegalArgumentException]
  }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/p&gt;


	&lt;p&gt;&lt;b&gt;&lt;i&gt;BowlingScorer.scala&lt;/b&gt;&lt;/i&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_scala "&gt;package com.om.example

class BowlingScorer(rollsSoFar:List[Int]){
   val rolls:List[Int] = rollsSoFar

  def roll(roll:Int) = {
    validate(roll)
    new BowlingScorer(rolls ++ Array(roll))
  }

  def validate(roll:Int) {
    if(invalidRoll(roll))
      throw new IllegalArgumentException(&amp;quot;Individaul rolls must be from 0 .. 10&amp;quot;)

    if(frameRollTooHigh(roll))
      throw new IllegalArgumentException(&amp;quot;Total of rolls for frame must not exceed 10&amp;quot;);

    if(willBeTooManyRolls)
      throw new IllegalArgumentException(&amp;quot;Game over, no more rolls allowed&amp;quot;)
  }

  def invalidRoll(roll:Int) = 
    (0 to 10 contains(roll)) == false  

  def frameRollTooHigh(roll:Int) =
    openScoreAt(indexToValidate) + roll &amp;gt; 10

  def willBeTooManyRolls = 
    tenthRolled(indexOf10thFrame) &amp;amp;&amp;amp; nextRollTooMany(indexOf10thFrame)

  def tenthRolled(tenthIndex:Int) = 
    tenthIndex &amp;lt; rolls.length

  def nextRollTooMany(tenthIndex: Int) = 
    allowedTenthFrameRolls(tenthIndex) &amp;lt; rollsInTenthFrame(tenthIndex) + 1

  def indexOf10thFrame = 
    (0 /: (1 until 10)) {(c, _) =&amp;gt; c + incrementAt(c)}

  def allowedTenthFrameRolls(index:Int) =
    if(isMark(index)) 3 else 2

  def rollsInTenthFrame(index: Int) =
    rolls.length - index

  def indexToValidate =
    if(onFirstThrow) rolls.length else rolls.length - 1

  def onFirstThrow = {
    var index = 0
    while(index &amp;lt; rolls.length)
      if(isStrike(index)) index += 1 else index += 2
    index == rolls.length
  }

  def scoreAt(frame:Int) = 
    ((0,0) /: (1 to frame)) { (t, _) =&amp;gt;  
      (t._1 + scoreAtIndex(t._2), t._2 + incrementAt(t._2))
    }._1

  def score = scoreAt(10)

  def scoreAtIndex(index:Int) =
    if(isMark(index)) markScoreAt(index) else openScoreAt(index)

  def incrementAt(index:Int) =
    if(isStrike(index)) 1 else 2

  def isMark(index:Int) =
    isStrike(index) || isSpare(index)

  def isStrike(index:Int) =
    valueAt(index) == 10

  def markScoreAt(index:Int) =
    sumNext(index, 3)

  def isSpare(index:Int) =
    openScoreAt(index) == 10 &amp;amp;&amp;amp; valueAt(index) != 10

  def openScoreAt(index:Int) =
    sumNext(index, 2)

  def sumNext(index:Int, count:Int) =
    (0 /: (index until index+count))(_ + valueAt(_))

  def valueAt(index:Int) = 
    if(rolls.length &amp;gt; index) rolls(index) else 0
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/p&gt;</description>
      <pubDate>Wed, 07 Oct 2009 00:51:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:92053ad6-01f8-4086-abbe-55dd0e6088d9</guid>
      <author>Brett Schuchert</author>
      <link>http://blog.objectmentor.com/articles/2009/10/07/scala-bowling-kata-still-in-the-middle-i-suppose</link>
      <category>Schuchert's Scattered Synapses </category>
      <category>Scala</category>
      <category>bdd</category>
      <category>specs</category>
      <category>bowling</category>
      <category>kata</category>
    </item>
    <item>
      <title>Scala Bowling Kata - somewhere in the middle...</title>
      <description>I need to do some work with Scala to update our Concurrency in Java class. We want to demonstrate some other approaches to concurrency, e.g., Scala Actors (among others). I began by shaving yaks:
	&lt;ul&gt;
	&lt;li&gt;Installed the &lt;a href="http://www.scala-lang.org/node/94"&gt;Eclipse Scala Plugin&lt;/a&gt;&lt;/li&gt;
		&lt;li&gt;Installed Scala using Mac Ports&lt;/li&gt;
		&lt;li&gt;Figured out how to get those things playing nice (the plugin page pretty much did that, but in a nutshell, add a few jar files to the classpath)&lt;/li&gt;
	&lt;/ul&gt;


Next, I wanted to use some &lt;span class="caps"&gt;BDD&lt;/span&gt; tool. I&amp;#8217;m going to try and stop using the term &lt;span class="caps"&gt;TDD&lt;/span&gt; simply because the T, which stands for Test in &lt;span class="caps"&gt;TDD&lt;/span&gt;, really means &amp;#8220;desired behavior&amp;#8221;. I considered calling it Trait Driven Development, but:
	&lt;ul&gt;
	&lt;li&gt;We don&amp;#8217;t need &lt;span class="caps"&gt;YADT&lt;/span&gt; &amp;#8211; Yet another damn term&lt;/li&gt;
		&lt;li&gt;Trait is a heavily overloaded word&lt;/li&gt;
		&lt;li&gt;I like the term &lt;span class="caps"&gt;BDD&lt;/span&gt; better and it fits.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Anyway, one such choice was &lt;a href="http://code.google.com/p/specs/"&gt;Specs&lt;/a&gt;, which is what I decided to use.&lt;/p&gt;


So back to yak shaving:
	&lt;ul&gt;
	&lt;li&gt;I added another jar to my classpath in Eclipse&lt;/li&gt;
		&lt;li&gt;&lt;a href="http://code.google.com/p/specs/wiki/RunningSpecs#Run_your_specification_with_JUnit4_in_Eclipse"&gt;Then read how to get it running in Eclipse&lt;/a&gt;. Not too bad, I suppose.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;So now I need to learn Scala. Sure, I&amp;#8217;ve used it, but far less than Ruby. So it took me several hours to get specs running along with writing some Scala code to score a game &amp;#8211; I&amp;#8217;m glad I know the domain at least.&lt;/p&gt;


	&lt;p&gt;I wanted to make similar behaviors to the ones I wrote for the &lt;a href="http://blog.objectmentor.com/articles/2009/10/01/bowling-game-kata-in-ruby"&gt;Ruby version&lt;/a&gt;, which I did.&lt;/p&gt;


However, unlike the Ruby version, I was curious what would happen if I:
	&lt;ul&gt;
	&lt;li&gt;Took an approach similar to Uncle Bob &amp;#8211; strikes take one slot in an array&lt;/li&gt;
		&lt;li&gt;Added input validation&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;On the one hand, there are some interesting things I managed to create. On the other hand, I&amp;#8217;ve got a bit of a mess. I have a stateful object to avoid passing parameters so that I can write some of the code cleanly. I know I need to add in an intermediate computational object, and I&amp;#8217;m going to get to that. However, I wanted to get feedback on what I&amp;#8217;ve put out there so far.&lt;/p&gt;


Specifically, 
	&lt;ul&gt;
	&lt;li&gt;What do you think of the (bdd-style) examples from specc?&lt;/li&gt;
		&lt;li&gt;What is the correct way to write the Times(20).Do( ...) thing I came up with, there&lt;i&gt; &lt;b&gt;has&lt;/b&gt;&lt;/i&gt; be a better way? &lt;/li&gt;
		&lt;li&gt;For the part of the bowling scoring code that is not stateful (read this as, does not violate the &lt;span class="caps"&gt;SRP&lt;/span&gt;), what do you think of it?&lt;/li&gt;
		&lt;li&gt;How would you remove most/all of the state (other than the individual rolls) out of the Bowling scorer class? (Or would you choose to have the roll() method return a new instance of BowlingScorer with the new score recorded?)&lt;/li&gt;
		&lt;li&gt;Notice that the class maintains a mini state machine in the form of tracking whether the first ball of he current frame (not tracked) has or has not been thrown. That&amp;#8217;s only there to be able to perform input validation. I considered:
	&lt;ul&gt;
	&lt;li&gt;Walking the array&lt;/li&gt;
		&lt;li&gt;Going to 2 slots for every frame (making it easy to find the frame)&lt;/li&gt;
		&lt;li&gt;Storing a frame object (ok, I didn&amp;#8217;t really consider it, but I did think about it)&lt;/li&gt;
		&lt;li&gt;The mini state machine&lt;/li&gt;
	&lt;/ul&gt;
	&lt;/li&gt;
		&lt;li&gt;nextFrameScore uses the index instance variable, and changes it. This both violates command-query separation and demonstrates a violation of the &lt;span class="caps"&gt;SRP&lt;/span&gt;, but it made the scoreAt method look nice.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;An interesting side effect is that scoring marks (strikes and spares) uses the same approach, sum up three rolls total.&lt;/p&gt;


	&lt;p&gt;I know this needs work. What I&amp;#8217;ve got works according to its current specification (its examples), so in a sense, that&amp;#8217;s a good thing because I&amp;#8217;ve already stared experimenting with trying out different solutions. However, I am painfully aware of how unaware I am of Scala at the moment, so your (hopefully gentle) feedback will tell me what I need to learn next.&lt;/p&gt;


	&lt;p&gt;Looking forward to the virtual beating &amp;#8230;&lt;/p&gt;


	&lt;p&gt;Brett&lt;/p&gt;


Here are the two files I&amp;#8217;ve created so far (and to be clear, all of the examples pass):
&lt;p&gt;&lt;/p&gt;
&lt;b&gt;&lt;i&gt;BowlingScorerExampleGroup.scala&lt;/b&gt;&lt;/i&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_scala "&gt;package com.om.example

import org.specs._

object BowlingScorerExampleGroup extends SpecificationWithJUnit {
  var scorer = new BowlingScorer();

  def roll(value:Int) {
    scorer.roll(value) 
  }

  def rollMany(rolls:Int, value:Int) {
    0.until(rolls).foreach { arg =&amp;gt; scorer.roll(value) }
  }

  def haveAScoreOf(expected:Int) {
    scorer.score must_== expected
  }

  def strike {
    roll(10)
  }

  def spare {
    rollMany(2, 5) 
  }

  abstract class IDo {
    def Do(block: =&amp;gt; Unit) 
  }

  def Times(count:Int): IDo = {
    return new IDo {
      def Do(block: =&amp;gt; Unit) {
        1.to(count).foreach( arg =&amp;gt; block )
      }
    }
  }

  &amp;quot;A Newly Created Bowling Scorer&amp;quot; should {
    haveAScoreOf(0)
  }

  &amp;quot;A game with all 0's&amp;quot; should {
    Times(20).Do( roll(0) )
    haveAScoreOf(0)
  }

  &amp;quot;A game with all 1's&amp;quot; should {
    Times(20).Do { roll(1) }
    haveAScoreOf(20)
  }

  &amp;quot;A game with a single spare followed by a 5&amp;quot; should {
    spare
    roll(5)
    haveAScoreOf(20)
  }

  &amp;quot;A game with all 5's&amp;quot; should {
    Times(10).Do( spare ) 
    roll(5)
    haveAScoreOf(150)
  }

  &amp;quot;A game with a single strike followed by a 4&amp;quot; should {
    strike
    roll(4)
    haveAScoreOf(18)
  }

  &amp;quot;A game with a strike, spare then an open frame with two 3's&amp;quot; should {
    strike
    spare
    Times(2).Do( roll(3) )
    haveAScoreOf(39)
  }

  &amp;quot;A game with strike, spare then an open frame with two 3's&amp;quot; should {
    spare
    strike
    Times(2).Do( roll(3) )
    haveAScoreOf(42)
  }

  &amp;quot;A Dutch 200 game, Spare-Strike&amp;quot; should {
    Times(5).Do { 
      spare 
      strike
    }
    spare
    haveAScoreOf(200)
  }

  &amp;quot;A Dutch 200 game, Strike-Spare&amp;quot; should {
    Times(5).Do { 
      strike
      spare 
    }
    strike
    haveAScoreOf(200)
  } 

  &amp;quot;A Perfect game&amp;quot; should {
    Times(12).Do( strike ) 
    haveAScoreOf(300)
  }

  &amp;quot;The score for each frame of a Perfect game, each frame&amp;quot; should {
    Times(12).Do( strike ) 
    1.to(10).foreach{ frame =&amp;gt; scorer.scoreAt(frame) must_== 30 * frame }
  }

  &amp;quot;An individaul roll of &amp;gt; 10&amp;quot; should {
    roll(11) must throwA[IllegalArgumentException]
  }

  &amp;quot;An iniviaul roll of &amp;lt; 0&amp;quot; should {
    roll(-1) must throwA[IllegalArgumentException]
  }

  &amp;quot;A frame trying to contain more than 10 pins&amp;quot; should {
    roll(8)
    roll(3) must throwA[IllegalArgumentException]
  }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

	&lt;p&gt;&lt;b&gt;&lt;i&gt;BowlingScorer.scala&lt;/b&gt;&lt;/i&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_scala "&gt;package com.om.example

class BowlingScorer {
  var rolls:Array[Int] = Array()
  var index:Int = 0
  var firstBallInFrameThrown: Boolean = false;

  def roll(roll:Int) = {
    validate(roll)
    record(roll)
  }

  def validate(roll:Int) {
    if((0).to(10).contains(roll) == false)
      throw new IllegalArgumentException(&amp;quot;Individaul rolls must be from 0 .. 10&amp;quot;)

    if(openScoreAt(indexToValidate) + roll &amp;gt; 10)
      throw new IllegalArgumentException(&amp;quot;Total of rolls for frame must not exceed 10&amp;quot;);
  }

  def record(roll: Int) {
    rolls = rolls ++ Array(roll)
    firstBallInFrameThrown = firstBallInFrameThrown == false &amp;amp;&amp;amp; roll != 10
  }

  def indexToValidate = {
    if(firstBallInFrameThrown) rolls.length - 1 else rolls.length
  }

  def scoreAt(frame:Int) = {
    1.to(frame).foldLeft(0) { (total, frame) =&amp;gt;  total + nextFrameScore  }
  }

  def score = {
    scoreAt(10)
  }

  def nextFrameScore = {
    var result = 0;
    if(isStrike(index)) {
      result += markScoreAt(index)
      index += 1
    } else if(isSpare(index)) {
      result += markScoreAt(index);
      index += 2
    } else {
      result += openScoreAt(index);
      index += 2
    }
    result
  }

  def isStrike(index:Int) = {
    valueAt(index) == 10
  }

  def markScoreAt(index:Int) = {
    sumNext(index, 3)
  }

  def isSpare(index:Int) = {
    openScoreAt(index) == 10
  }

  def openScoreAt(index:Int) = {
    sumNext(index, 2)
  }

  def sumNext(index:Int, count:Int) = {
    index.until(index+count).foldLeft(0)(_ + valueAt(_))
  }

  def valueAt(index:Int) = {
    if(rolls.length &amp;gt; index) rolls.apply(index) else 0
  }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/p&gt;</description>
      <pubDate>Mon, 05 Oct 2009 23:33:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:23cd72fc-e4b5-4dbd-b219-e4bb2e4b92c7</guid>
      <author>Brett Schuchert</author>
      <link>http://blog.objectmentor.com/articles/2009/10/05/scala-bowling-kata-somewhere-in-the-middle</link>
      <category>Schuchert's Scattered Synapses </category>
      <category>Scala</category>
      <category>bdd</category>
      <category>specs</category>
      <category>bowling</category>
      <category>kata</category>
    </item>
    <item>
      <title>&amp;quot;Programming Scala&amp;quot; Is Now Available</title>
      <description>&lt;p&gt;&lt;a href="http://oreilly.com/catalog/9780596155957/"&gt;Programming Scala&lt;/a&gt; is finally available online at &lt;a href="http://www.amazon.com/Programming-Scala-Animal-Guide-Wampler/dp/0596155956/ref=sr_1_3?ie=UTF8&amp;#38;s=books&amp;#38;qid=1253575163&amp;#38;sr=8-3"&gt;Amazon&lt;/a&gt;, &lt;a href="http://oreilly.com/catalog/9780596155957/"&gt;O&amp;#8217;Reilly&lt;/a&gt;,  &lt;a href="http://my.safaribooksonline.com/9780596801908"&gt;Safari&lt;/a&gt;, and hopefully at other online and physical bookstores, too. If you have trouble finding it, just memorize the &lt;span class="caps"&gt;ISBN&lt;/span&gt;, 9780596155957, to aid your search. ;)&lt;/p&gt;


&lt;center&gt;&lt;a href="http://oreilly.com/catalog/9780596155957/"&gt;&lt;img src="http://blog.objectmentor.com/files/prog_scala_mech_cover_front_503x660.png" style="border: 1px solid #7E205F;" /&gt;&lt;/a&gt;&lt;/center&gt;

	&lt;p&gt;&lt;br/&gt;You can download the complete code examples &lt;a href="http://examples.oreilly.com/9780596155964/"&gt;here&lt;/a&gt;. If you want to &amp;#8220;try before you buy&amp;#8221;, see our &lt;a href="http://programming-scala.labs.oreilly.com/"&gt;labs&lt;/a&gt; site.&lt;/p&gt;


	&lt;p&gt;I pitched the book idea just over one year ago. &lt;a href="http://twitter.com/al3x"&gt;Alex Payne&lt;/a&gt;, my co-author, was also talking to O&amp;#8217;Reilly about a book, so we joined forces. It&amp;#8217;s been a fast ride.&lt;/p&gt;


	&lt;p&gt;This book is for you if you are an experienced developer who wants a comprehensive, but fast introduction to Scala. We try to convince you why we like Scala so much, but we also tell you about those dark corners and gotchas that you&amp;#8217;ll find in any language. We even preview the forthcoming 2.8 version of Scala. I hope you&amp;#8217;ll give &lt;a href="http://oreilly.com/catalog/9780596155957/"&gt;Programming Scala&lt;/a&gt; a look.&lt;/p&gt;</description>
      <pubDate>Mon, 21 Sep 2009 17:48:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:5d439b0f-ba3b-4e25-a0d5-b8023a94dbd4</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2009/09/21/programming-scala-is-now-available</link>
      <category>Dean's Deprecations</category>
      <category>Scala</category>
      <category>programmingscala</category>
      <category>books</category>
      <enclosure type="image/png" url="http://blog.objectmentor.com/files/prog_scala_mech_cover_front_503x6601.png" length="172253"/>
    </item>
    <item>
      <title>A Milestone for &amp;quot;Programming Scala&amp;quot;</title>
      <description>&lt;p&gt;My co-author, &lt;a href="http://al3x.net/about.html"&gt;Alex Payne&lt;/a&gt;, and I hit a major milestone today for &lt;a href="http://programmingscala.com"&gt;Programming Scala&lt;/a&gt;. After a feverish holiday weekend of writing, we finished all the remaining sections of the book. This morning, we released it to O&amp;#8217;Reilly&amp;#8217;s crack production team. &amp;#8220;If you love something, set it free&amp;#8221; or something sappy like that. Of course, the corollary is, &amp;#8220;if it doesn&amp;#8217;t come back, hunt it down and kill it&amp;#8230;&amp;#8221;&lt;/p&gt;


	&lt;p&gt;But I digress. There will be more reviews and final edits. You can still add your comments online using the link above. However, the text is essentially done. It  has started the final journey that will turn our words into a book, something of a life-long dream of mine that I waited too long to achieve. Kudo&amp;#8217;s to Alex for pursuing this dream early in his career. If it&amp;#8217;s a dream you have entertained, know that it&amp;#8217;s never too late.&lt;/p&gt;


	&lt;p&gt;On the other hand, whatever modest qualities the book possesses reflect the combined years of experience that Alex and I have acquired, sometimes painfully. In a way, as I reflect on what I wrote, &lt;a href="http://programmingscala.com"&gt;Programming Scala&lt;/a&gt; is a software design book masquerading as a language book. The truly seductive quality of Scala is that it makes elegant design concepts possible, which is why I&amp;#8217;ve placed so much faith in the language.&lt;/p&gt;


	&lt;p&gt;Alex posted his &lt;a href="http://al3x.net/2009/07/07/the-tapir-book.html"&gt; own thoughts&lt;/a&gt; on the project, which I hope you&amp;#8217;ll take the time to read. I&amp;#8217;m grateful for his insights and experience with Scala, the elegance of his prose in the book, and the great work he&amp;#8217;s done at Twitter, which caused me to get so addicted to Twitter that I spent too much time tweeting over the last year, which meant I had to work my proverbial butt off this past weekend to get the book done. Thanks a lot!!&lt;/p&gt;</description>
      <pubDate>Tue, 07 Jul 2009 21:02:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:b68bf7ee-86b3-4c22-9765-7e4825258747</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2009/07/07/a-milestone-for-programming-scala</link>
      <category>Dean's Deprecations</category>
      <category>Scala</category>
      <category>programmingscala</category>
      <category>books</category>
    </item>
    <item>
      <title>Bay-Area Scala Enthusiasts (BASE) Meeting: What's New In Scala 2.8</title>
      <description>&lt;p&gt;This week is JavaOne in San Francisco. The Bay-Area Scala Enthusiasts (BASE) held their monthly meeting. Martin Odersky, the creator of Scala, was the special guest. He discussed what&amp;#8217;s new In Scala 2.8, followed by Q&amp;#38;A. We met at Twitter HQ.&lt;/p&gt;


	&lt;p&gt;These are my notes, focusing primarily on Martin&amp;#8217;s presentation, and filled in afterwards with additional details. Any transcription errors or erroneous extrapolations are my own fault. It&amp;#8217;s also late in the day&amp;#8230;&lt;/p&gt;


	&lt;p&gt;Some of the features are not yet in the &lt;span class="caps"&gt;SVN&lt;/span&gt; trunk, so don&amp;#8217;t assume my examples actually work! See the &lt;a href="http://scala-lang.org"&gt;scala-lang.org&lt;/a&gt; for more details on Scala 2.8 features.&lt;/p&gt;


	&lt;p&gt;There are a few more months before it is released. A preview is planned for July, followed by the final release in September or October.&lt;/p&gt;


	&lt;h2&gt;New Features&lt;/h2&gt;


	&lt;p&gt;Here are the new features for this release.&lt;/p&gt;


	&lt;h3&gt;Named and Default Arguments&lt;/h3&gt;


	&lt;p&gt;Scala method parameters can be declared to with default values, so callers don&amp;#8217;t have to specify a value and the &lt;code&gt;implicit&lt;/code&gt; convention doesn&amp;#8217;t have to be used. The default &amp;#8220;values&amp;#8221; aren&amp;#8217;t limited to constants. Any valid expression can be used. Here is an example that I made up (not in Martin&amp;#8217;s slides) that illustrates both specifying and using one default argument and using named arguments.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def joiner(strings: List[String], separator: String = " ") = strings.mkString(separator)

val strs = List("Now", "is", "the", "time", "for", "all", "good", "men", "...")
println(joiner(strs))
println(joiner(strs, "|"))
println(joiner(strings = strs, separator = "-"))
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Named and default arguments enable an elegant enhancement to case classes. It&amp;#8217;s great that I can declare a succinct value class like this.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
case class Person(firstName: String, lastName: String, age: Int)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;What if I want to make a copy that modifies one or more fields. There&amp;#8217;s no elegant way to add such a method in 2.7 without implementing every permutation, that is every possible combination of fields I might want to change. The new &lt;code&gt;copy&lt;/code&gt; method will make this easy.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
case class Person(firstName: String, lastName: String, age: Int)

val youngPerson = Person("Dean", "Wampler", 29)
val oldPerson = youngPerson copy (age = 30)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;I&amp;#8217;m using the infix notation for method invocation on the last line (&lt;em&gt;i.e.,&lt;/em&gt; it&amp;#8217;s equivalent to &lt;code&gt;... youngPerson.copy(...)&lt;/code&gt;). I can specify any combination of the fields I want to change in the list passed to &lt;code&gt;copy&lt;/code&gt;. The generated implementation of &lt;code&gt;copy&lt;/code&gt; will use the current values of any other fields as the default values.&lt;/p&gt;


	&lt;p&gt;The implementation looks something like this.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
case class Person(firstName: String, lastName: String, age: Int) {
  def copy (fName: String = this.firstName, 
            lName: String = this.lastName, 
            aje: Int = this.age) = new Person(fName, lName, aje)
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Quite elegant, once you have default and named arguments!!&lt;/p&gt;


	&lt;p&gt;Defaults for parameters can&amp;#8217;t refer to previous parameters in the list, unless the function is curried. (I&amp;#8217;m not sure I got this right, nor do I understand the reasons why this is true &amp;#8211; if it&amp;#8217;s true!)&lt;/p&gt;


	&lt;p&gt;By the way, Martin reminded us that method parameters are always evaluated left to right at the call site. Do you remember the rules for Java, C++, C#,...?&lt;/p&gt;


	&lt;h3&gt;Nested Annotations&lt;/h3&gt;


	&lt;p&gt;Annotations can now be nested, which is important for using some of the standard annotation definitions in the &lt;span class="caps"&gt;JDK&lt;/span&gt; and &lt;span class="caps"&gt;JEE&lt;/span&gt;. This feature also exploits named and default arguments.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
@Annotation1(foo = @Annotation2)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;h3&gt;Package Objects&lt;/h3&gt;


	&lt;p&gt;People have complained that they want to define top-level definitions for a package, but they have to put those definitions, like types and methods, in an &lt;code&gt;object&lt;/code&gt; or &lt;code&gt;class&lt;/code&gt;, which doesn&amp;#8217;t quite fit and it&amp;#8217;s awkward for referencing through package and type qualification. The problem was especially obvious when the team started working on the major reorganization of the collections (discussed below). So, Scala 2.8 will support &amp;#8220;package objects&amp;#8221;.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package object scala {
  type List[+T] = scala.collection.immutable.List
  val List = scala.collection.immutable.List
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Our friend &lt;code&gt;List&lt;/code&gt; is now moved to &lt;code&gt;scala.collection.immutable.List&lt;/code&gt;, but we would still like to reference it as if it were in the &lt;code&gt;scala&lt;/code&gt; package. The definition defines a package-level &lt;code&gt;type&lt;/code&gt; and &lt;code&gt;val&lt;/code&gt; the effectively make List accessible in the &lt;code&gt;scala&lt;/code&gt; scope. In Scala 2.7 you would have to do something like the following (ignoring &lt;code&gt;Predef&lt;/code&gt; for a moment).&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package scala {
  object toplevel {
    type List[+T] = scala.collection.immutable.List
    val List = scala.collection.immutable.List
  }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;But then you would have to reference &lt;code&gt;List&lt;/code&gt; using &lt;code&gt;scala.toplevel.List&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;Now, they got around this problem previously by putting a bunch of stuff like this in &lt;code&gt;Predef&lt;/code&gt; and importing it automatically, but that has several disadvantages.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;&lt;code&gt;Predef&lt;/code&gt; is a big, amorphous collection of stuff.&lt;/li&gt;
		&lt;li&gt;You can&amp;#8217;t define your own &lt;code&gt;Predef&lt;/code&gt; with the same convenient usage semantics, &lt;em&gt;i.e.,&lt;/em&gt; no special import required and no way to reference definitions like &lt;code&gt;package.type&lt;/code&gt;. You would have to use the alternative I just showed with &lt;code&gt;toplevel&lt;/code&gt; in the middle.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Package objects give you a place for definitions that you want to appear at the package scope without having to define them in a singleton object or class.&lt;/p&gt;


	&lt;p&gt;Finally, besides types and fields as shown, package objects can also define methods. They can also inherit from traits and classes.&lt;/p&gt;


	&lt;h3&gt;@specialized&lt;/h3&gt;


	&lt;p&gt;Scala generics are fully specified at declaration time using a uniform representation, not when they are used, like C++ templates. This supports the way Java works, where there isn&amp;#8217;t a giant link step to resolve all references, &lt;em&gt;etc.&lt;/em&gt; However, this has a major performance disadvantage for generic types when they are actually used with &lt;code&gt;AnyVal&lt;/code&gt; types that Scala optimizes to primitives.&lt;/p&gt;


	&lt;p&gt;For example, any closures require the use of FunctionN[T1, T2, ...], &lt;em&gt;e.g.,&lt;/em&gt;&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def m[T](x: T, f: T =&amp;gt; T) = f(x)

m(2, (x:Int) =&amp;gt; x * 2)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;f&lt;/code&gt; closure in the definition of &lt;code&gt;m&lt;/code&gt; will require instantiation of &lt;code&gt;Function2[T,T]&lt;/code&gt;. However, when use &lt;code&gt;AnyVal&lt;/code&gt; classes, as in the last line , this has the effect of causing primitive boxing and unboxing several times, hurting performance when this is completely unnecessary in the special case of primitives being used. This is also bad for arrays and some other data structures.&lt;/p&gt;


	&lt;p&gt;The new &lt;code&gt;@specialized&lt;/code&gt; annotation fixes this problem by causing scala to generate different versions of the user-specified generic type or method for each of the primitive types.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def m[@specialized T](x: T, f: T =&amp;gt; T) = f(x)

m(2, (x:Int) =&amp;gt; x * 2)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;There is a real risk of an explosion of code. Consider what would have to be generated to support every type permutation for &lt;code&gt;Function22&lt;/code&gt;! For this reason they only do cases with up to two type parameters in the library. You can also choose to annotate only some of the type parameters, as appropriate, and the annotation will support parameters that let you limit the primitive types that will be supported, &lt;em&gt;e.g.,&lt;/em&gt; only &lt;code&gt;Ints&lt;/code&gt; and &lt;code&gt;Longs&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;This feature is not yet in the 2.8 trunk, but it will be soon.&lt;/p&gt;


	&lt;h2&gt;Improved Collections&lt;/h2&gt;


	&lt;p&gt;Collections are getting a major revamp. First they want to eliminate gratuitous differences in package structure and implementations. In many cases, the &lt;code&gt;map&lt;/code&gt; method and others have to be redefined for each basic collection type, rather than shared between them.&lt;/p&gt;


	&lt;h3&gt;New Collections Design&lt;/h3&gt;


	&lt;p&gt;The new version of the library will support the following.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Uniform structure.&lt;/li&gt;
		&lt;li&gt;Every operation is implemented only once.&lt;/li&gt;
		&lt;li&gt;Selection of building blocks in a separate package called &lt;code&gt;scala.collection.generic&lt;/code&gt;. These are normally only used by implementers of immutable and mutable collections.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Because of the reorganization, some Scala 2.7 source code won&amp;#8217;t be compatible with 2.8 without modifications.&lt;/p&gt;


	&lt;h2&gt;Better Tools&lt;/h2&gt;


	&lt;ul&gt;
	&lt;li&gt;The &lt;span class="caps"&gt;REPL&lt;/span&gt; will have command completion, in addition to other enhancements.&lt;/li&gt;
		&lt;li&gt;They have greatly improved the &lt;span class="caps"&gt;IDE&lt;/span&gt; and compiler interface. Miles Sabin and Iulian Dragos worked on this with Martin. There is limited and somewhat unstable support in Eclipse now.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;h2&gt;New Control Abstractions&lt;/h2&gt;


	&lt;p&gt;Several new control abstractions are being introduced.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;Continuations will be supported with a compiler plugin.&lt;/li&gt;
		&lt;li&gt;Scala has not had the &lt;code&gt;break&lt;/code&gt; keyword. It will now exist, but as a library method.&lt;/li&gt;
		&lt;li&gt;Scala will optimize trampolining tail calls (&lt;em&gt;e.g.&lt;/em&gt;, &lt;code&gt;foo1&lt;/code&gt; tail calls &lt;code&gt;foo2&lt;/code&gt;, which tail calls &lt;code&gt;foo1&lt;/code&gt;, and back and forth).&lt;/li&gt;
	&lt;/ul&gt;


	&lt;h2&gt;More features&lt;/h2&gt;


	&lt;ul&gt;
	&lt;li&gt;The Swing wrapper library has been enhanced.&lt;/li&gt;
		&lt;li&gt;The performance has been improved in several ways.
	&lt;ul&gt;
	&lt;li&gt;Structural type dispatch&lt;/li&gt;
		&lt;li&gt;Actors&lt;/li&gt;
		&lt;li&gt;Vectors, sets, and maps. Their long-term goal is to implement the fastest ones available for the &lt;span class="caps"&gt;JVM&lt;/span&gt;.&lt;/li&gt;
	&lt;/ul&gt;&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;These changes are not yet in the trunk.&lt;/p&gt;


	&lt;h2&gt;Beyond 2.8&lt;/h2&gt;


Longer term, they plan significant improvements in support for parallelism and concurrency, including new concurrency models besides actors, such as:
	&lt;ul&gt;
	&lt;li&gt;Transactions (STM)&lt;/li&gt;
		&lt;li&gt;Data parallelism&lt;/li&gt;
		&lt;li&gt;stream processing&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Clojure is influencing this. Martin praised the competition ;) Fortunately, the original designer of the data structures and algorithms used heavily by Clojure is working on Scala versions. (Name?)&lt;/p&gt;


	&lt;p&gt;Doug Lea wants to work with the team on concurrency data structures. The lack of closures in Java makes this effort difficult in Java.&lt;/p&gt;


	&lt;p&gt;There is some exciting work in advanced type system support for guaranteeing actor isolation and effect tracking. For example, this technology wouuld allow actors to exchange references to big objects without copying them while ensuring that they aren&amp;#8217;t modified concurrently.&lt;/p&gt;


	&lt;p&gt;On a final note, Bill Wake described a conversation he had with Joshua Bloch today who admitted that the time has arrived for him to look seriously at Scala. A possible endorsement from Joshua Bloch would be a major step for Scala.&lt;/p&gt;</description>
      <pubDate>Fri, 05 Jun 2009 02:13:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:b489a56a-baea-484e-b0d6-686ecc39d34c</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2009/06/05/bay-area-scala-enthusiasts-base-meeting-whats-new-in-scala-2-8</link>
      <category>Dean's Deprecations</category>
      <category>Scala</category>
      <category>JavaOne</category>
    </item>
    <item>
      <title>Is the Supremacy of Object-Oriented Programming Over?</title>
      <description>&lt;p&gt;I never expected to see this. When I started my career, Object-Oriented Programming (OOP) was going mainstream. For many problems, it was and still is a natural way to &lt;em&gt;modularize&lt;/em&gt; an application. It grew to (mostly) rule the world. Now it seems that the supremacy of objects may be coming to an end, of sorts.&lt;/p&gt;


	&lt;p&gt;I say this because of recent trends in our industry and my hands-on experience with many enterprise and Internet applications, mostly at client sites. You might be thinking that I&amp;#8217;m referring to the mainstream breakout of Functional Programming (FP), which is happening right now. The &lt;em&gt;killer app&lt;/em&gt; for FP is concurrency. We&amp;#8217;ve all heard that more and more applications must be concurrent these days (which doesn&amp;#8217;t necessarily mean multithreaded). When we remove side effects from functions and disallow mutable variables, our concurrency issues largely go away. The success of the Actor model of concurrency, as used to great effect in &lt;a href="http://erlang.org/"&gt;Erlang&lt;/a&gt;, is one example of a functional-style approach. The rise of &lt;a href="http://labs.google.com/papers/mapreduce.html"&gt;map-reduce&lt;/a&gt; computations is another example of a functional technique going mainstream. A related phenomenon is the emergence of key-value store databases, like &lt;a href="http://labs.google.com/papers/bigtable.html"&gt;BigTable&lt;/a&gt; and &lt;a href="http://couchdb.apache.org/"&gt;CouchDB&lt;/a&gt;, is a reaction to the overhead of &lt;span class="caps"&gt;SQL&lt;/span&gt; databases, when the performance cost of the Relational Model isn&amp;#8217;t justified. These databases are typically managed with functional techniques, like map-reduce.&lt;/p&gt;


	&lt;p&gt;But actually, I&amp;#8217;m thinking of something else. Hybrid languages like &lt;a href="http://scala-lang.org"&gt;Scala&lt;/a&gt;, &lt;a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/"&gt;F#&lt;/a&gt;, and &lt;a href="http://caml.inria.fr/ocaml/index.en.html"&gt;OCaml&lt;/a&gt; have demonstrated that &lt;span class="caps"&gt;OOP&lt;/span&gt; and FP can complement each other. In a given context, they let you use the idioms that make the most sense for your particular needs. For example, immutable &amp;#8220;objects&amp;#8221; and functional-style pattern matching is a killer combination.&lt;/p&gt;


	&lt;p&gt;What&amp;#8217;s really got me thinking that objects are losing their supremacy is a very mundane problem. It&amp;#8217;s a problem that isn&amp;#8217;t new, but like concurrency, it just seems to grow worse and worse.&lt;/p&gt;


	&lt;p&gt;The problem is that there is never a stable, clear object model in applications any more. What constitutes a &lt;code&gt;BankAccount&lt;/code&gt; or &lt;code&gt;Customer&lt;/code&gt; or whatever is fluid. It changes with each iteration. It&amp;#8217;s different from one subsystem to another even within the &lt;em&gt;same&lt;/em&gt; iteration! I see a lot of misfit object models that try to be all things to all people, so they are bloated and the teams that own them can&amp;#8217;t be agile. The other extreme is &amp;#8220;balkanization&amp;#8221;, where each subsystem has its own model. We tend to think the latter case is bad. However, is lean and mean, but non-standard, worse than bloated, yet standardized?&lt;/p&gt;


	&lt;p&gt;The fact is, for a lot of these applications, it&amp;#8217;s just data. The ceremony of object wrappers doesn&amp;#8217;t carry its weight. Just put the data in a hash map (or a list if you don&amp;#8217;t need the bits &amp;#8220;labeled&amp;#8221;) and then process the collection with your iterate, map, and reduce functions. This may sound heretical, but how much Java code could you delete today if you replaced it with a stored procedure?&lt;/p&gt;


	&lt;p&gt;These alternatives won&amp;#8217;t work for all situations, of course. Sometimes polymorphism carries its weight. Unfortunately, it&amp;#8217;s too tempting to use objects as if more is always better, like &lt;a href="http://www.google.com/search?client=safari&amp;#38;rls=en-us&amp;#38;q=more+cowbell&amp;#38;ie=UTF-8&amp;#38;oe=UTF-8"&gt;cow bell&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;So what would replace objects for supremacy? Well, my point is really that there is no one true way. We&amp;#8217;ve led ourselves down the wrong path. Or, to be more precise, we followed a single, very good path, but we didn&amp;#8217;t know when to take a different path.&lt;/p&gt;


	&lt;p&gt;Increasingly, the best, most nimble designs I see use objects with a light touch; shallow hierarchies, small objects that try to obey the Single Responsibility Principle, composition rather than inheritance, &lt;em&gt;etc.&lt;/em&gt; Coupled with a liberal use of functional idioms (like iterate, map, and reduce), these designs strike the right balance between the protection of data hiding &lt;em&gt;vs.&lt;/em&gt; openness for easy processing. By the way, you can build these designs in almost any of our popular languages. Some languages make this easier than others, of course.&lt;/p&gt;


	&lt;p&gt;Despite the hype, I think &lt;a href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html"&gt;Domain-Specific Languages&lt;/a&gt; (DSLs) are also very important and worth mentioning in this context. (&lt;a href="http://en.wikipedia.org/wiki/Language-oriented_programming"&gt;Language-Oriented Programming&lt;/a&gt; &amp;#8211; &lt;span class="caps"&gt;LOP&lt;/span&gt; &amp;#8211; generalizes these ideas). It&amp;#8217;s true that people drink the &lt;span class="caps"&gt;DSL&lt;/span&gt; Kool-Aid and create a mess. However, when used appropriately, DSLs reduce a program to its &lt;a href="http://en.wikipedia.org/wiki/Essential_complexity"&gt;essential complexity&lt;/a&gt;, while hiding and modularizing the &lt;a href="http://en.wikipedia.org/wiki/Accidental_complexity"&gt;accidental complexity&lt;/a&gt; of the implementation. When it becomes easy to write a user story in code, we won&amp;#8217;t obsess as much over the details of a &lt;code&gt;BankAccount&lt;/code&gt; as they change from one story to another. We will embrace more flexible data persistence models, too.&lt;/p&gt;


	&lt;p&gt;Back to &lt;span class="caps"&gt;OOP&lt;/span&gt; and FP, I see the potential for their combination to lead to a rebirth of the old vision of &lt;em&gt;software components&lt;/em&gt;, but that&amp;#8217;s a topic for another blog post.&lt;/p&gt;</description>
      <pubDate>Mon, 20 Apr 2009 21:45:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:69ac398f-694c-4e0b-bc13-a8765608f6cf</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2009/04/20/is-the-supremacy-of-object-oriented-programming-over</link>
      <category>Dean's Deprecations</category>
      <category>Agile Methods</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>design</category>
      <category>OOP</category>
      <category>FP</category>
      <category>polyglot</category>
      <category>Polyparadigm</category>
      <category>Scala</category>
      <category>F</category>
      <category>OCaml</category>
      <category>MapReduce</category>
      <category>BigTable</category>
      <category>CouchDB</category>
      <category>SQL</category>
      <category>dsl</category>
      <category>LOP</category>
    </item>
    <item>
      <title>Pat Eyler Interviews Dean Wampler and Alex Payne on &amp;quot;Programming Scala&amp;quot;.</title>
      <description>&lt;p&gt;&lt;a href="http://twitter.com/gnupate"&gt;Pat Eyler&lt;/a&gt; posted an &lt;a href="http://on-ruby.blogspot.com/2009/03/dean-wampler-and-alex-payne-author.html"&gt;interview&lt;/a&gt; with &lt;a href="http://twitter.com/al3x"&gt;Alex Payne&lt;/a&gt; and me (Dean Wampler), which we conducted over email. We dish on Scala, Functional Programming, and our forthcoming book &lt;a href="http://oreilly.com/catalog/9780596157746/index.html"&gt;Programming Scala&lt;/a&gt;.&lt;/p&gt;</description>
      <pubDate>Tue, 17 Mar 2009 12:48:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:a53602a4-52af-4c4f-8bb5-105224343067</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2009/03/17/pat-eyler-interviews-dean-wampler-and-alex-payne-on-programming-scala</link>
      <category>Dean's Deprecations</category>
      <category>Scala</category>
    </item>
    <item>
      <title>1st Ever Chicago Area Scala Enthusiasts (CASE) Meeting Tonight</title>
      <description>&lt;p&gt;Tonight is our first meeting, at the ThoughtWorks offices in the Aon building downtown. If you&amp;#8217;re going and you haven&amp;#8217;t &lt;span class="caps"&gt;RSVP&lt;/span&gt;&amp;#8217;ed, either send a tweet to @chicagoscala or reply here &lt;span class="caps"&gt;ASAP&lt;/span&gt;!&lt;/p&gt;


	&lt;p&gt;Hope to see you there. Our meetings will be the 3rd Thursday of each month.&lt;/p&gt;</description>
      <pubDate>Thu, 19 Feb 2009 18:17:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:2f572e0d-c976-46a2-a1ec-790ea17072b6</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2009/02/19/1st-ever-chicago-area-scala-enthusiasts-case-meeting-tonight</link>
      <category>Dean's Deprecations</category>
      <category>Public Speaking Engagements</category>
      <category>Scala</category>
      <category>CASE</category>
      <category>chicagoscala</category>
    </item>
    <item>
      <title>Organizing a Chicago Area Scala Enthusiasts (CASE) Group</title>
      <description>&lt;p&gt;I&amp;#8217;m organizing a group in Chicago for people interested in Scala, called the Chicago Area Scala Enthusiasts (CASE). If you&amp;#8217;re interested, join the &lt;a href="http://groups.google.com/group/chicagoscala"&gt;google group&lt;/a&gt; for more information.&lt;/p&gt;</description>
      <pubDate>Sat, 17 Jan 2009 17:02:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:1d72bceb-aa03-475c-aa1f-38b7b78be11f</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2009/01/17/organizing-a-chicago-area-scala-enthusiasts-case-group</link>
      <category>Dean's Deprecations</category>
      <category>Public Speaking Engagements</category>
      <category>Scala</category>
      <category>chicago</category>
    </item>
    <item>
      <title>Adopting New JVM Languages in the Enterprise (Update)</title>
      <description>&lt;p&gt;(Updated to add Groovy, which I should have mentioned the first time. Also mentioned Django under Python.)&lt;/p&gt;


	&lt;p&gt;This is an exciting time to be a Java programmer. The pace of innovation for the Java language is slowing down, in part due to concerns that the language is growing too big and in part due to economic difficulties at Sun, which means there are fewer developers assigned to Java. However, the real &lt;em&gt;crown jewel&lt;/em&gt; of the Java ecosystem, the &lt;span class="caps"&gt;JVM&lt;/span&gt;, has become an attractive platform for new languages. These languages give us exciting new opportunities for growth, while preserving our prior investment in code and deployment infrastructure.&lt;/p&gt;


	&lt;p&gt;This post emphasizes practical issues of evaluating and picking new &lt;span class="caps"&gt;JVM&lt;/span&gt; languages for an established Java-based enterprise.&lt;/p&gt;


	&lt;p&gt;The Interwebs are full of technical comparisons between Java and the different languages, &lt;em&gt;e.g.,&lt;/em&gt; why language X fixes Java&amp;#8217;s perceived issue Y. I won&amp;#8217;t rehash those arguments here, but I will describe some language features, as needed.&lt;/p&gt;


	&lt;p&gt;A similar &amp;#8220;polyglot&amp;#8221; trend is happening on the .NET platform.&lt;/p&gt;


	&lt;h2&gt;The New &lt;span class="caps"&gt;JVM&lt;/span&gt; Languages&lt;/h2&gt;


	&lt;p&gt;I&amp;#8217;ll limit my discussion to these representative (and best known) alternative languages for the &lt;span class="caps"&gt;JVM&lt;/span&gt;.&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;&lt;a href="http://jruby.codehaus.org/"&gt;JRuby&lt;/a&gt; &amp;#8211; Ruby running on the &lt;span class="caps"&gt;JVM&lt;/span&gt;.&lt;/li&gt;
		&lt;li&gt;&lt;a href="http://scala-lang.org"&gt;Scala&lt;/a&gt; &amp;#8211; A hybrid object-oriented and functional language that runs on .NET as well as the &lt;span class="caps"&gt;JVM&lt;/span&gt;. (Disclaimer: I&amp;#8217;m co-writing a book on Scala for O&amp;#8217;Reilly.)&lt;/li&gt;
		&lt;li&gt;&lt;a href="http://clojure.org"&gt;Clojure&lt;/a&gt; &amp;#8211; A Lisp dialect.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;I picked these languages because they seem to be the most likely candidates for most enterprises considering a new &lt;span class="caps"&gt;JVM&lt;/span&gt; language, although some of the languages listed below could make that claim.&lt;/p&gt;


	&lt;p&gt;There are other deserving languages besides these three, but I don&amp;#8217;t have the time to do them justice. Hopefully, you can generalize the subsequent discussion for these other languages.&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;&lt;a href="http://groovy.codehaus.org/"&gt;Groovy&lt;/a&gt; &amp;#8211; A dynamically-typed language designed specifically for interoperability with Java. It will appeal to teams that want a dynamically-typed language that is closer to Java than Ruby. With &lt;a href="http://grails.org/"&gt;Grails&lt;/a&gt;, you have a combination that&amp;#8217;s comparable to Ruby on Rails.&lt;/li&gt;
		&lt;li&gt;&lt;a href="http://jython.org/"&gt;Jython&lt;/a&gt; &amp;#8211; The first non-Java language ported to the &lt;span class="caps"&gt;JVM&lt;/span&gt;, started by Jim Hugunin in 1997. Most of my remarks about JRuby are applicable to Jython. &lt;a href="http://www.djangoproject.com/"&gt;Django&lt;/a&gt; is the Python analog of Rails. If your Java shop already has a lot of Python, consider Jython.&lt;/li&gt;
		&lt;li&gt;&lt;a href="http://www.fandev.org/"&gt;Fan&lt;/a&gt; &amp;#8211; A hybrid object-oriented and functional language that runs on .NET, too. It has a lot of similarities to Scala, like a scripting-language feel.&lt;/li&gt;
		&lt;li&gt;&lt;a href="http://kenai.com/projects/ioke/"&gt;Ioke&lt;/a&gt; &amp;#8211; (pronounced &amp;#8220;eye-oh-key&amp;#8221;) An innovative language developed by Ola Bini and inspired by Io and Lisp. This is the newest language discussed here. Hence, it has a small following, but a lot of potential. The Io/Lisp-flavored syntax will be more challenging to average Java developers than Scala, JRuby, Jython, Fan, and JavaScript.&lt;/li&gt;
		&lt;li&gt;JavaScript, &lt;em&gt;e.g.,&lt;/em&gt; &lt;a href="http://www.mozilla.org/rhino/"&gt;Rhino&lt;/a&gt; &amp;#8211; Much maligned and misunderstood (&lt;em&gt;e.g.,&lt;/em&gt; due to buggy and inconsistent browser implementations), JavaScript continues to gain converts as an alternative scripting language for Java applications. It is the default scripting language supported by the &lt;span class="caps"&gt;JDK 6&lt;/span&gt; scripting interface.&lt;/li&gt;
		&lt;li&gt;&lt;a href="http://projectfortress.sun.com/Projects/Community/"&gt;Fortress&lt;/a&gt; &amp;#8211; A language designed as a replacement for high-performance &lt;span class="caps"&gt;FORTRAN&lt;/span&gt; for industrial and academic &amp;#8220;number crunching&amp;#8221;. This one will interest scientists and engineers&amp;#8230;&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;Note: Like a lot of people, I use the term &lt;em&gt;scripting language&lt;/em&gt; to refer to languages with a lightweight syntax, usually dynamically typed. The name reflects their convenience for &amp;#8220;scripting&amp;#8221;, but that quality is sometimes seen as pejorative; they aren&amp;#8217;t seen as &amp;#8220;serious&amp;#8221; languages. I reject this view.&lt;/p&gt;


	&lt;p&gt;To learn more about what people are doing on the &lt;span class="caps"&gt;JVM&lt;/span&gt; today (with some guest .NET presentations), a good place to start is the recent &lt;a href="http://openjdk.java.net/projects/mlvm/jvmlangsummit/"&gt;&lt;span class="caps"&gt;JVM&lt;/span&gt; Language Summit&lt;/a&gt;.&lt;/p&gt;


	&lt;h2&gt;Criteria For Evaluating New &lt;span class="caps"&gt;JVM&lt;/span&gt; Languages&lt;/h2&gt;


	&lt;p&gt;I&amp;#8217;ll frame the discussion around a few criteria you should consider when evaluating language choices. I&amp;#8217;ll then discuss how each of the languages address those criteria. Since we&amp;#8217;re restricting ourselves to &lt;span class="caps"&gt;JVM&lt;/span&gt; languages, I assume that each language compiles to valid byte code, so code in the new language and code written in Java can call each other, at least at some level. The &amp;#8220;some level&amp;#8221; part will be one criterion. Substitute X for the language you are considering.&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;&lt;strong&gt;Interoperability&lt;/strong&gt;: How easily can X code invoke Java code and &lt;em&gt;vice versa&lt;/em&gt;? Specifically:
	&lt;ol&gt;
	&lt;li&gt;Create objects (&lt;em&gt;i.e.,&lt;/em&gt; call &lt;code&gt;new Foo(...)&lt;/code&gt;).&lt;/li&gt;
		&lt;li&gt;Call methods on an object.&lt;/li&gt;
		&lt;li&gt;Call static methods on a class.&lt;/li&gt;
		&lt;li&gt;Extend a class.&lt;/li&gt;
		&lt;li&gt;Implement an interface.&lt;/li&gt;
	&lt;/ol&gt;
	&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Object Model&lt;/strong&gt;: How different is the object model of X compared to Java&amp;#8217;s object model? (This is somewhat tied to the previous point.)&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;New &amp;#8220;Ideas&amp;#8221;&lt;/strong&gt;: Does X support newer programming trends:
	&lt;ol&gt;
	&lt;li&gt;Functional Programming.&lt;/li&gt;
		&lt;li&gt;Metaprogramming.&lt;/li&gt;
		&lt;li&gt;Easier approaches to writing robust concurrent applications.&lt;/li&gt;
		&lt;li&gt;Easier support for processing &lt;span class="caps"&gt;XML&lt;/span&gt;, SQL queries, &lt;em&gt;etc.&lt;/em&gt;&lt;/li&gt;
		&lt;li&gt;Support &lt;a href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html"&gt;internal &lt;span class="caps"&gt;DSL&lt;/span&gt;&lt;/a&gt; creation.&lt;/li&gt;
		&lt;li&gt;Easier presentation-tier development of web and thick-client UI&amp;#8217;s.&lt;/li&gt;
	&lt;/ol&gt;
	&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Stability&lt;/strong&gt;: How stable is the language, in terms of:
	&lt;ol&gt;
	&lt;li&gt;Lack of Bugs.&lt;/li&gt;
		&lt;li&gt;Stability of the language&amp;#8217;s syntax, semantics, and library &lt;span class="caps"&gt;API&lt;/span&gt;&amp;#8217;s. (All the languages can call Java &lt;span class="caps"&gt;API&lt;/span&gt;&amp;#8217;s.)&lt;/li&gt;
	&lt;/ol&gt;
	&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Performance&lt;/strong&gt;: How does code written in X perform?&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Adoption&lt;/strong&gt;: Is X easy to learn and use?&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Tool Support&lt;/strong&gt;: What about editors, &lt;span class="caps"&gt;IDE&lt;/span&gt;&amp;#8217;s, code coverage, &lt;em&gt;etc.&lt;/em&gt;&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Deployment&lt;/strong&gt;: How are apps and libraries written in X deployed? 
	&lt;ol&gt;
	&lt;li&gt;Do I have to modify my existing infrastructure, management, &lt;em&gt;etc.&lt;/em&gt;?&lt;/li&gt;
	&lt;/ol&gt;&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;The &lt;strong&gt;Interoperability&lt;/strong&gt; point affects ease of adoption and use with a legacy Java code base. The &lt;strong&gt;Object Model&lt;/strong&gt; and &lt;strong&gt;Adoption&lt;/strong&gt; points address the barrier to adoption from the learning point of view. The &lt;strong&gt;New &amp;#8220;Ideas&amp;#8221;&lt;/strong&gt; point asks what each language brings to development that is not available in Java (or poorly supported) and is seen as valuable to the developer. Finally, &lt;strong&gt;Stability&lt;/strong&gt;, &lt;strong&gt;Performance&lt;/strong&gt;, and &lt;strong&gt;Deployment&lt;/strong&gt; address very practical issues that a candidate production language must address.&lt;/p&gt;


	&lt;h2&gt;Comparing the Languages&lt;/h2&gt;


	&lt;h3&gt;JRuby&lt;/h3&gt;


	&lt;p&gt;JRuby is the most popular alternative &lt;span class="caps"&gt;JVM&lt;/span&gt; langauge, driven largely by interest in &lt;a href="http://ruby-lang.org"&gt;Ruby&lt;/a&gt; and &lt;a href="http://rubyonrails.org/"&gt;Ruby on Rails&lt;/a&gt;.&lt;/p&gt;


	&lt;h4&gt;Interoperability&lt;/h4&gt;


	&lt;p&gt;Ruby&amp;#8217;s object model is a little different than Java&amp;#8217;s, but JRuby provides straightforward coding idioms that make it easy to call Java from JRuby. Calling JRuby from Java requires the &lt;span class="caps"&gt;JSR 223&lt;/span&gt; scripting interface or a similar approach, unless JRuby is used to compile the Ruby code to byte code first. In that case, shortcuts are possible, which are well documented.&lt;/p&gt;


	&lt;h4&gt;Object Model&lt;/h4&gt;


	&lt;p&gt;Ruby&amp;#8217;s object model is a little different than Java&amp;#8217;s. Ruby support &lt;em&gt;mixin&lt;/em&gt;-style modules, which behave like interfaces &lt;em&gt;with&lt;/em&gt; implementations. So, the Ruby object model needs to be learned, but it is straightforward or the Java developer.&lt;/p&gt;


	&lt;h4&gt;New Ideas&lt;/h4&gt;


	&lt;p&gt;JRuby brings closures to the &lt;span class="caps"&gt;JVM&lt;/span&gt;, a much desired feature that probably won&amp;#8217;t be added in the forthcoming Java 7. Using closures, Ruby supports a number of functional-style iterative operations, like mapping, filtering, and reducing/folding. However, Ruby does not fully support functional programming.&lt;/p&gt;


	&lt;p&gt;Ruby uses dynamic-typing instead of static-typing, which it exploits to provide extensive and powerful metaprogramming facilities.&lt;/p&gt;


	&lt;p&gt;Ruby doesn&amp;#8217;t offer any specific enhancements over Java for safe, robust concurrent programming.&lt;/p&gt;


	&lt;p&gt;Ruby &lt;span class="caps"&gt;API&lt;/span&gt;&amp;#8217;s make &lt;span class="caps"&gt;XML&lt;/span&gt; processing and database access relatively easy. Ruby on Rails is legendary for improving the productivity of web developers and similar benefits are available for thick-client developers using other libraries.&lt;/p&gt;


	&lt;p&gt;Ruby is also one of the best languages for defining &amp;#8220;internal&amp;#8221; &lt;span class="caps"&gt;DSL&lt;/span&gt;&amp;#8217;s, which are used to great affect in Rails (&lt;em&gt;e.g.,&lt;/em&gt; &lt;em&gt;ActiveRecord&lt;/em&gt;).&lt;/p&gt;


	&lt;h4&gt;Stability&lt;/h4&gt;


	&lt;p&gt;JRuby and Ruby are very stable and are widely used in production. JRuby is believed to be the best performing Ruby platform.&lt;/p&gt;


	&lt;p&gt;The Ruby syntax and &lt;span class="caps"&gt;API&lt;/span&gt; are undergoing some significant changes in the current 1.9.X release, but migration is not a major challenge.&lt;/p&gt;


	&lt;h4&gt;Performance&lt;/h4&gt;


	&lt;p&gt;JRuby is believed to be the best performing Ruby platform. While it is a topic of hot debate, Ruby and most dynamically-typed languages have higher runtime overhead compared to statically-typed languages. Also, the &lt;span class="caps"&gt;JVM&lt;/span&gt; has some known performance issues for dynamically-typed languages, some of which will be fixed in &lt;span class="caps"&gt;JDK 7&lt;/span&gt;.&lt;/p&gt;


	&lt;p&gt;As always, enterprises should profile code written in their languages of choice to pick the best one for each particular task.&lt;/p&gt;


	&lt;h4&gt;Adoption&lt;/h4&gt;


	&lt;p&gt;Ruby is very easy to learn, although effective use of advanced techniques like metaprogramming require some time to master. JRuby-specific idioms are also easy to master and are well documented.&lt;/p&gt;


	&lt;h4&gt;Tool Support&lt;/h4&gt;


	&lt;p&gt;Ruby is experiencing tremendous growth in tool support. &lt;span class="caps"&gt;IDE&lt;/span&gt; support still lags support for Java, but IntelliJ, NetBeans, and Eclipse are working on Ruby support. JRuby users can exploit many Java tools.&lt;/p&gt;


	&lt;p&gt;Code analysis tools and testing tools (TDD and &lt;span class="caps"&gt;BDD&lt;/span&gt; styles) are now better than Java&amp;#8217;s.&lt;/p&gt;


	&lt;h4&gt;Deployment&lt;/h4&gt;


	&lt;p&gt;JRuby applications, even Ruby on Rails applications, can be deployed as jars or wars, requiring no modifications to an existing java-based infrastructure. Teams use this approach to minimize the &amp;#8220;friction&amp;#8221; of adopting Ruby, while also getting the performance benefits of the &lt;span class="caps"&gt;JVM&lt;/span&gt;.&lt;/p&gt;


	&lt;p&gt;Because JRuby code is byte code at runtime, it can be managed with &lt;span class="caps"&gt;JMX&lt;/span&gt;, &lt;em&gt;etc.&lt;/em&gt;&lt;/p&gt;


	&lt;h3&gt;Scala&lt;/h3&gt;


	&lt;p&gt;Scala is a statically-typed language that supports an improved object model (with a full &lt;em&gt;mixin&lt;/em&gt; mechanism called &lt;em&gt;traits&lt;/em&gt;; similar to Ruby &lt;em&gt;modules&lt;/em&gt;) and full support for functional programming, following a design goal of the inventor of Scala, Martin Odersky, that these two &lt;em&gt;paradigms&lt;/em&gt; can be integrated, despite some surface incompatibilities.  Odersky was involved in the design of Java generics (through earlier research languages) and he wrote the original version of the current &lt;code&gt;javac&lt;/code&gt;. The name is a contraction of &amp;#8220;scalable language&amp;#8221;, but the first &amp;#8220;a&amp;#8221; is pronounced like &amp;#8220;ah&amp;#8221;, not long as in the word &amp;#8220;hay&amp;#8221;.&lt;/p&gt;


	&lt;p&gt;The syntax looks like a cross between Ruby (method definitions start with the &lt;code&gt;def&lt;/code&gt; keyword) and Java (&lt;em&gt;e.g.,&lt;/em&gt; curly braces). Type inferencing and other syntactic conventions significantly reduce the &amp;#8220;cluuter&amp;#8221;, such as the number of explicit type declarations (&amp;#8220;annotations&amp;#8221;) compared to Java. Scala syntax is very succinct, sometimes even more so than Ruby!  For more on Scala, see also my previous blog postings, &lt;a href="http://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i"&gt;part 1&lt;/a&gt;, &lt;a href="http://blog.objectmentor.com/articles/2008/08/05/the-seductions-of-scala-part-ii-functional-programming"&gt;part 2&lt;/a&gt;, &lt;a href="http://blog.objectmentor.com/articles/2008/08/14/the-seductions-of-scala-part-iii-concurrent-programming"&gt;part 3&lt;/a&gt;, and this related post on &lt;a href="http://blog.objectmentor.com/articles/2008/09/27/traits-vs-aspects-in-scala"&gt;traits vs. aspects&lt;/a&gt;.&lt;/p&gt;


	&lt;h4&gt;Interoperability&lt;/h4&gt;


	&lt;p&gt;Scala&amp;#8217;s has the most seamless interoperability with Java of any of the languages discussed here. This is due in part to Scala&amp;#8217;s static typing and &amp;#8220;closed&amp;#8221; classes (as opposed to Ruby&amp;#8217;s &amp;#8220;open&amp;#8221; classes). It is &lt;em&gt;trivial&lt;/em&gt; to import and use Java classes, implement interfaces, &lt;em&gt;etc&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Direct &lt;span class="caps"&gt;API&lt;/span&gt; calls from Java to Scala are also supported. The developer needs to know how the names of Scala methods are encoding in byte code. For example, Scala methods can have &amp;#8220;operator&amp;#8221; names, like &amp;#8221;+&amp;#8221;. In the byte code, that name will be &amp;#8221;$plus&amp;#8221;.&lt;/p&gt;


	&lt;h4&gt;Object Model&lt;/h4&gt;


	&lt;p&gt;Scala&amp;#8217;s object model extends Java&amp;#8217;s model with &lt;em&gt;traits&lt;/em&gt;, which support flexble &lt;em&gt;mixin&lt;/em&gt; composition. Traits behave like interfaces &lt;em&gt;with&lt;/em&gt; implementations. The Scala object model provides other sophisticated features for building &amp;#8220;scalable applications&amp;#8221;.&lt;/p&gt;


	&lt;h4&gt;New Ideas&lt;/h4&gt;


	&lt;p&gt;Scala brings full support for functional programming to the &lt;span class="caps"&gt;JVM&lt;/span&gt;, including first-class function and closures. Other aspects of functional programming, like immutable variables and side-effect free functions, are encouraged by the language, but not mandated, as Scala is not a pure functional language. (Functional programming is very effective strategy for writing tread-safe programs, &lt;em&gt;etc.&lt;/em&gt;) Scala&amp;#8217;s &lt;em&gt;Actor&lt;/em&gt; library is a port of Erlang&amp;#8217;s &lt;em&gt;Actor&lt;/em&gt; library, a message-based concurrency approach.&lt;/p&gt;


	&lt;p&gt;In my view, the &lt;em&gt;Actor model is the best general-purpose approach to concurrency.&lt;/em&gt; There are times when multi-threaded code is needed for performance, but not for most concurrent applications. (Note: there are Actor libraries for Java, &lt;em&gt;e.g.,&lt;/em&gt; &lt;a href="http://www.malhar.net/sriram/kilim/"&gt;Kilim&lt;/a&gt;.)&lt;/p&gt;


	&lt;p&gt;Scala has very good support for building internal &lt;span class="caps"&gt;DSL&lt;/span&gt;&amp;#8217;s, although it is not quite as good as Ruby&amp;#8217;s features for this purpose. It has a combinator parser library that makes external &lt;span class="caps"&gt;DSL&lt;/span&gt; creation comparatively easy. Scala also offers some innovative &lt;span class="caps"&gt;API&lt;/span&gt;&amp;#8217;s for &lt;span class="caps"&gt;XML&lt;/span&gt; processing and Swing development.&lt;/p&gt;


	&lt;h4&gt;Stability&lt;/h4&gt;


	&lt;p&gt;Scala is over 5 years old and it is very stable. The &lt;span class="caps"&gt;API&lt;/span&gt; and syntax continue to evolve, but no major, disruptive changes are expected. In fact, the structure of the language is such that almost all changes occur in libraries, not the language grammar.&lt;/p&gt;


	&lt;p&gt;There are some well-known production deployments, such as back-end services at &lt;a href="http://twitter.com"&gt;twitter&lt;/a&gt;.&lt;/p&gt;


	&lt;h4&gt;Performance&lt;/h4&gt;


	&lt;p&gt;Scala provides comparable performance to Java, since it is very close &amp;#8220;structurally&amp;#8221; to Java code at the byte-code level, given the static typing and &amp;#8220;closed&amp;#8221; classes. Hence, Scala can exploit &lt;span class="caps"&gt;JVM&lt;/span&gt; optimizations that aren&amp;#8217;t available to dynamically-typed languages.&lt;/p&gt;


	&lt;p&gt;However, Scala will also benefit from planned improvements to support dynamically-typed languages, such as tail-call optimizations (which Scala current does in the compiler.) Hence, Scala &lt;em&gt;probably&lt;/em&gt; has marginally better performance than JRuby, in general. If true, Scala may be more appealing than JRuby as a general-purpose, &lt;em&gt;systems&lt;/em&gt; language, where performance is &lt;em&gt;critical&lt;/em&gt;.&lt;/p&gt;


	&lt;h4&gt;Adoption&lt;/h4&gt;


	&lt;p&gt;Scala is harder to learn and master than JRuby, because it is a more comprehensive language. It not only supports a sophisticated object model, but it also supports functional programming, type inferencing, &lt;em&gt;etc.&lt;/em&gt; In my view, the extra effort will be rewarded with higher productivity. Also, because it is closer to Java than JRuby and Clojure, new users will be able to start using it quickly as a &amp;#8220;better object-oriented Java&amp;#8221;, while they continue to learn the more advanced features, like functional programming, that will accelerate their productivity over the long term.&lt;/p&gt;


	&lt;h4&gt;Tool Support&lt;/h4&gt;


	&lt;p&gt;Scala support in &lt;span class="caps"&gt;IDE&lt;/span&gt;&amp;#8217;s still lags support for Java, but it is improving. IntelliJ, NetBeans, and Eclipse now support Scala with plugins. Maven and ant are widely used as the build tool for Scala applications. Several excellent &lt;span class="caps"&gt;TDD&lt;/span&gt; and &lt;span class="caps"&gt;BDD&lt;/span&gt; libraries are available.&lt;/p&gt;


	&lt;h4&gt;Deployment&lt;/h4&gt;


	&lt;p&gt;Scala applications are packaged and deployed just like Java applications, since Scala files are compiled to class files. A Scala runtime jar is also required.&lt;/p&gt;


	&lt;h3&gt;Clojure&lt;/h3&gt;


	&lt;p&gt;Of the three new &lt;span class="caps"&gt;JVM&lt;/span&gt; languages discussed here, Clojure is the least like Java, due to its Lisp syntax and innovative &amp;#8220;programming model&amp;#8221;. Yet it is also the most innovative and exciting new &lt;span class="caps"&gt;JVM&lt;/span&gt; language for many people. Clojure interoperates with Java code, but it emphasizes functional programming. Unlike the other languages, Clojure does not support object-oriented programming. Instead, it relies on mechanisms like multi-methods and macros to address design problems for which &lt;span class="caps"&gt;OOP&lt;/span&gt; is often used.&lt;/p&gt;


	&lt;p&gt;One exciting innovation in Clojure is support for &lt;em&gt;software transactional memory&lt;/em&gt;, which uses a database-style transactional approach to concurrent modifications of in-memory, mutable state. &lt;span class="caps"&gt;STM&lt;/span&gt; is somewhat controversial. You can google for arguments about its practicality, &lt;em&gt;etc.&lt;/em&gt; However, Clojure&amp;#8217;s implementation appears to be successful.&lt;/p&gt;


	&lt;p&gt;Clojure also has other innovative ways of supporting &amp;#8220;principled&amp;#8221; modification of mutable data, while encouraging the use of immutable data. These features with &lt;span class="caps"&gt;STM&lt;/span&gt; are the basis of Clojure&amp;#8217;s approach to robust concurrency.&lt;/p&gt;


	&lt;p&gt;Finally, Clojure implements several optimizations in the compiler that are important for functional programming, such as optimizing tail call recursion.&lt;/p&gt;


	&lt;p&gt;Disclaimer: I know less about Clojure than JRuby and Scala. While I have endeavored to get the facts right, there may be errors in the following analysis. Feedback is welcome.&lt;/p&gt;


	&lt;h4&gt;Interoperability&lt;/h4&gt;


	&lt;p&gt;Despite the Lisp syntax and functional-programming emphasis, Clojure interoperates with Java. Calling java from Clojure uses direct &lt;span class="caps"&gt;API&lt;/span&gt; calls, as for JRuby and Scala. Calling Clojure from Java is a more involved. You have to create Java proxies on the Clojure side to generate the byte code needed on the Java side. The idioms for doing this are straightforward, however.&lt;/p&gt;


	&lt;h4&gt;Object Model&lt;/h4&gt;


	&lt;p&gt;Clojure is not an object-oriented language. However, in order to interoperate with Java code, Clojure supports implementing interfaces and instantiating Java objects. Otherwise, Clojure offers a significant departure for develops well versed in object-oriented programming, but with little functional programming experience.&lt;/p&gt;


	&lt;h4&gt;New Ideas&lt;/h4&gt;


	&lt;p&gt;Clojure brings to the &lt;span class="caps"&gt;JVM&lt;/span&gt; full support for functional programming and popular Lisp concepts like macros, multi-methods, and powerful metaprogramming. It has innovative approaches to safe concurrency, including &amp;#8220;principled&amp;#8221; mechanisms for supporting mutable state, as discussed previously.&lt;/p&gt;


	&lt;p&gt;Clojure&amp;#8217;s succinct syntax and built-in libraries make processing &lt;span class="caps"&gt;XML&lt;/span&gt; succinct and efficient. &lt;span class="caps"&gt;DSL&lt;/span&gt; creation is also supported using Lisp mechanisms, like macros.&lt;/p&gt;


	&lt;h4&gt;Stability&lt;/h4&gt;


	&lt;p&gt;Clojure is the newest of the three languages profiled here. Hence, it may be the most subject to change. However, given the nature of Lisps, it is more likely that changes will occur in libraries than the language itself. Stability in terms of bugs does not appear to be an issue.&lt;/p&gt;


	&lt;p&gt;Clojure also has the fewest known production deployments of the three languages. However, industry adoption is expected to happen rapidly.&lt;/p&gt;


	&lt;h4&gt;Performance&lt;/h4&gt;


	&lt;p&gt;Clojure supports type &amp;#8220;hints&amp;#8221; to assist in optimizing performance. The preliminary discussions I have seen suggest that Clojure offers very good performance.&lt;/p&gt;


	&lt;h4&gt;Adoption&lt;/h4&gt;


	&lt;p&gt;Clojure is more of a departure from Java than is Scala. It will require a motivated team that likes Lisp ;) However, such a team may learn Clojure faster than Scala, since Clojure is a simpler language, &lt;em&gt;e.g.,&lt;/em&gt; because it doesn&amp;#8217;t have its own object model. Also, Lisps are well known for being simple languages, where the real learning comes in understanding how to use it effectively!&lt;/p&gt;


	&lt;p&gt;However, in my view, as for Scala, the extra learning effort will be rewarded with higher productivity.&lt;/p&gt;


	&lt;h4&gt;Tool Support&lt;/h4&gt;


	&lt;p&gt;As a new language, tool support is limited. Most Clojure developers use Emacs with its excellent Lisp support. Many Java tools can be used with Clojure.&lt;/p&gt;


	&lt;h4&gt;Deployment&lt;/h4&gt;


	&lt;p&gt;Clojure deployment appears to be as straightforward as for the other languages. A Clojure runtime jar is required.&lt;/p&gt;


	&lt;h3&gt;Comparisons&lt;/h3&gt;


	&lt;p&gt;Briefly, let&amp;#8217;s review the points and compare the three languages.&lt;/p&gt;


	&lt;h4&gt;Interoperability&lt;/h4&gt;


	&lt;p&gt;All three languages make calling Java code straightforward. Scala interoperates most seamlessly. Scala code is easiest to invoke from Java code, using direct &lt;span class="caps"&gt;API&lt;/span&gt; calls, as long as you know how Scala encodes method names that have &amp;#8220;illegal&amp;#8221; characters (according to the &lt;span class="caps"&gt;JVM&lt;/span&gt; spec.). Calling JRuby and Clojure code from Java is more involved.&lt;/p&gt;


	&lt;p&gt;Therefore, if you expect to continue writing Java code that needs to make frequent &lt;span class="caps"&gt;API&lt;/span&gt; calls to the  code in the new language, Scala will be a better choice.&lt;/p&gt;


	&lt;h4&gt;Object Model&lt;/h4&gt;


	&lt;p&gt;Scala is closest to Java&amp;#8217;s object model. Ruby&amp;#8217;s object model is superficially similar to Scala&amp;#8217;s, but the dynamic nature of Ruby brings significant differences. Both extend Java&amp;#8217;s object model with &lt;em&gt;mixin&lt;/em&gt; composition through &lt;em&gt;traits&lt;/em&gt; (Scala) or &lt;em&gt;modules&lt;/em&gt; (Ruby), that act like &lt;em&gt;interfaces with implementations&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Clojure is quite different, with an emphasis on functional programming and no direct support for object-oriented programming.&lt;/p&gt;


	&lt;h4&gt;New Ideas&lt;/h4&gt;


	&lt;p&gt;JRuby brings the productivity and power of a dynamically-typed language to the &lt;span class="caps"&gt;JVM&lt;/span&gt;, along with the drawbacks. It also brings some functional idioms.&lt;/p&gt;


	&lt;p&gt;Scala and Clojure bring full support for functional programming. Scala provides a complete Actor model of concurrency (as a library). Clojure brings software transactional memory and other innovations for writing robust concurrent applications. JRuby and Ruby don&amp;#8217;t add anything specific for concurrency.&lt;/p&gt;


	&lt;p&gt;JRuby, like Ruby, is exceptionally good for writing internal &lt;span class="caps"&gt;DSL&lt;/span&gt;&amp;#8217;s. Scala is also very good and Clojure benefits from Lisp&amp;#8217;s support for &lt;span class="caps"&gt;DSL&lt;/span&gt; creation.&lt;/p&gt;


	&lt;h4&gt;Stability&lt;/h4&gt;


	&lt;p&gt;All the language implementations are of high quality. Scala is the most mature, but JRuby has the widest adoption in production.&lt;/p&gt;


	&lt;h4&gt;Performance&lt;/h4&gt;


	&lt;p&gt;Performance should be comparable for all, but JRuby and Clojure have to deal with some inefficiencies inherent to running dynamic languages on the &lt;span class="caps"&gt;JVM&lt;/span&gt;. Your mileage may vary, so &lt;em&gt;please&lt;/em&gt; run realistic profiling experiments on sample implementations that are representative of your needs. Avoid &amp;#8220;prematurely optimization&amp;#8221; when choosing a new language. Often, team productivity and &amp;#8220;time to market&amp;#8221; are more important than raw performance.&lt;/p&gt;


	&lt;h4&gt;Adoption&lt;/h4&gt;


	&lt;p&gt;JRuby is the the easiest of the three languages to learn and adopt if you already have some Ruby or Ruby on Rails code in your environment.&lt;/p&gt;


	&lt;p&gt;Scala has the lowest barrier to adoption because it is the language that most resembles Java &amp;#8220;philosophically&amp;#8221; (static typing, emphasis on object-oriented programming, &lt;em&gt;etc.&lt;/em&gt;). Adopters can start with Scala as a &amp;#8220;better Java&amp;#8221; and gradually learn the advanced features (&lt;em&gt;mixin&lt;/em&gt; composition with traits and functional programming). Scala will appeal the most to teams that prefer statically-typed languages, yet want some of the benefits of dynamically-typed languages, like a succinct syntax.&lt;/p&gt;


	&lt;p&gt;However, Scala is the most complex of the three languages, while Clojure requires the biggest conceptual leap from Java.&lt;/p&gt;


	&lt;p&gt;Clojure will appeal to teams willing to explore more radical departures from what they are doing now, with potentially great payoffs!&lt;/p&gt;


	&lt;h4&gt;Deployment&lt;/h4&gt;


	&lt;p&gt;Deployment is easy with all three languages. Scala is most like Java, since you normally compile to class files (there is a limited interpreter mode). JRuby and Clojure code can be interpreted at runtime or compiled.&lt;/p&gt;


	&lt;h2&gt;Summary and Conclusions&lt;/h2&gt;


	&lt;p&gt;All three choices (or comparable substitutions from the list of other languages), will provide a Java team with a more modern language, yet fully leverage the existing investment in Java. Scala is the easiest incremental change. JRuby brings the vibrant Ruby world to the &lt;span class="caps"&gt;JVM&lt;/span&gt;. Clojure offers the most innovative departures from Java.&lt;/p&gt;</description>
      <pubDate>Thu, 15 Jan 2009 01:40:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:391065da-b6e2-4f4e-b3a1-cc911d3955df</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2009/01/15/adopting-new-jvm-languages-in-the-enterprise</link>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>Agile Methods</category>
      <category>Scala</category>
      <category>JRuby</category>
      <category>clojure</category>
      <category>jvm</category>
      <category>enterprise</category>
      <category>Java</category>
    </item>
    <item>
      <title>Upcoming Speaking Engagements</title>
      <description>&lt;p&gt;I&amp;#8217;m speaking this Friday at &lt;a href="http://rubyconf.org/"&gt;RubyConf&lt;/a&gt; on &lt;a href="http://rubyconf.org/talks/46"&gt;Better Ruby Through Functional Programming&lt;/a&gt;. I&amp;#8217;ll introduce long-overlooked ideas from FP, why they are important for Ruby programmers, and how to use them in Ruby.&lt;/p&gt;


	&lt;p&gt;In two weeks, I&amp;#8217;m speaking on Wednesday, 11/19 at &lt;a href="http://qconsf.com/sf2008/"&gt;QCon San Francisco&lt;/a&gt; on &lt;a href="http://qconsf.com/sf2008/speaker/Dean+Wampler"&gt;Radical Simplification Through Polyglot and Poly-paradigm Programming&lt;/a&gt;. The idea of this talk is that combining the right languages and modularity paradigms (&lt;em&gt;i.e.,&lt;/em&gt; objects, functions, aspects) can simplify your code base and reduce the amount of code you have to write and manage, providing numerous benefits.&lt;/p&gt;


	&lt;p&gt;Back in Chicago, I&amp;#8217;m speaking at the &lt;a href="http://polyglotprogrammers.com/"&gt;Polyglot Programmer&amp;#8217;s&lt;/a&gt; meeting on &lt;a href="http://polyglotprogrammers.com/usa/illinois/chicago/"&gt;The Seductions of Scala&lt;/a&gt;, 11/13. It&amp;#8217;s an intro to the Scala language, which could become the language of choice for the &lt;span class="caps"&gt;JVM&lt;/span&gt;. I&amp;#8217;m repeating this talk at the &lt;a href="http://www.cjug.org/Wiki.jsp?page=2008.12.16.downtown"&gt;Chicago Java User&amp;#8217;s Group&lt;/a&gt; on 12/16. I&amp;#8217;m co-writing a book on Scala with &lt;a href="http://twitter.com/al3x"&gt;Alex Payne&lt;/a&gt;. O&amp;#8217;Reilly will be the publisher.&lt;/p&gt;


	&lt;p&gt;Incidently, Bob Martin is also speaking in Chicago on 11/13 at the &lt;a href="http://www.aplnchicago.org/"&gt;&lt;span class="caps"&gt;APLN&lt;/span&gt; Chicago&lt;/a&gt; meeting on &lt;a href="http://www.aplnchicago.org/Calendar.php"&gt;Software Professionalism&lt;/a&gt;.&lt;/p&gt;</description>
      <pubDate>Mon, 03 Nov 2008 18:13:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:4d0b05fe-743b-46a8-b236-625089da6095</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/11/03/upcoming-speaking-engagements</link>
      <category>Dean's Deprecations</category>
      <category>Public Speaking Engagements</category>
      <category>Agile Methods</category>
      <category>Clean Code</category>
      <category>talks</category>
      <category>RubyConf</category>
      <category>APLN</category>
      <category>Polyglot_Programmers</category>
      <category>Scala</category>
      <category>QCon</category>
    </item>
    <item>
      <title>A Scala-style &amp;quot;with&amp;quot; Construct for Ruby</title>
      <description>&lt;p&gt;Scala has a &amp;#8220;mixin&amp;#8221; construct called &lt;em&gt;traits&lt;/em&gt;, which are roughly analogous to Ruby &lt;em&gt;modules&lt;/em&gt;. They allow you to create reusable, modular bits of state and behavior and use them to compose classes and other traits or modules.&lt;/p&gt;


	&lt;p&gt;The syntax for using Scala traits is quite elegant. It&amp;#8217;s straightforward to implement the same syntax in Ruby and doing so has a few useful advantages.&lt;/p&gt;


	&lt;p&gt;For example, here is a Scala example that uses a trait to trace calls to a &lt;code&gt;Worker.work&lt;/code&gt; method.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
// run with "scala example.scala" 

class Worker {
    def work() = "work" 
}

trait WorkerTracer extends Worker {
    override def work() = "Before, " + super.work() + ", After" 
}

val worker = new Worker with WorkerTracer

println(worker.work())        // =&amp;gt; Before, work, After
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note that &lt;code&gt;WorkerTracer&lt;/code&gt; extends &lt;code&gt;Worker&lt;/code&gt; so it can override the &lt;code&gt;work&lt;/code&gt; method. Since Scala is statically typed, you can&amp;#8217;t just define an &lt;code&gt;override&lt;/code&gt; method and call &lt;code&gt;super&lt;/code&gt; unless the compiler knows there really is a &amp;#8220;super&amp;#8221; method!&lt;/p&gt;


	&lt;p&gt;Here&amp;#8217;s a Ruby equivalent.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# run with "ruby example.rb" 

module WorkerTracer
    def work; "Before, #{super}, After"; end
end

class Worker 
    def work; "work"; end
end

class TracedWorker &amp;lt; Worker 
  include WorkerTracer
end

worker = TracedWorker.new

puts worker.work          # =&amp;gt; Before, work, After
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note that we have to create a subclass, which isn&amp;#8217;t required for the Scala case (but can be done when desired).&lt;/p&gt;


	&lt;p&gt;If you know that you will always want to trace calls to &lt;code&gt;work&lt;/code&gt; in the Ruby case, you might be tempted to dispense with the subclass and just add &lt;code&gt;include WorkerTracer&lt;/code&gt; in &lt;code&gt;Worker&lt;/code&gt;. Unfortunately, this won&amp;#8217;t work. Due to the way that Ruby resolves methods, the version of &lt;code&gt;work&lt;/code&gt; in the module will not be found before the version defined in &lt;code&gt;Worker&lt;/code&gt; itself. Hence the subclass seems to be the only option.&lt;/p&gt;


	&lt;p&gt;However, we can work around this using metaprogramming. We can use &lt;code&gt;WorkerTracer#append_features(...)&lt;/code&gt;. What goes in the argument list? If we pass &lt;code&gt;Worker&lt;/code&gt;, then all instances of &lt;code&gt;Worker&lt;/code&gt; will be effected, but actually we&amp;#8217;ll still have the problem with the method resolution rules.&lt;/p&gt;


	&lt;p&gt;If we just want to affect one object &lt;em&gt;and&lt;/em&gt; work around the method resolution roles, then we need to pass the &lt;em&gt;singleton class&lt;/em&gt; (or &lt;em&gt;eigenclass&lt;/em&gt; or &lt;em&gt;metaclass&lt;/em&gt; ...) for the object, which you can get with the following expression.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
metaclass = class &amp;lt;&amp;lt; worker; self; end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;So, to encapsulate all this and to get back to the original goal of implementing &lt;code&gt;with&lt;/code&gt;-style semantics, here is an implementation that adds a &lt;code&gt;with&lt;/code&gt; method to &lt;code&gt;Object&lt;/code&gt;, wrapped in an &lt;a href="http://rspec.info"&gt;rspec&lt;/a&gt; example.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# run with "spec ruby_with_spec.rb" 

require 'rubygems'
require 'spec'

# Warning, monkeypatching Object, especially with a name
# that might be commonly used is fraught with peril!!

class Object
  def with *modules
    metaclass = class &amp;lt;&amp;lt; self; self; end
    modules.flatten.each do |m|
      m.send :append_features, metaclass
    end
    self
  end
end

module WorkerTracer
    def work; "Before, #{super}, After"; end
end

module WorkerTracer1
    def work; "Before1, #{super}, After1"; end
end

class Worker 
    def work; "work"; end
end

describe "Object#with" do
  it "should make no changes to an object if no modules are specified" do
    worker = Worker.new.with
    worker.work.should == "work" 
  end

  it "should override any methods with a module's methods of the same name" do
    worker = Worker.new.with WorkerTracer
    worker.work.should == "Before, work, After" 
  end

  it "should stack overrides for multiple modules" do
    worker = Worker.new.with(WorkerTracer).with(WorkerTracer1)
    worker.work.should == "Before1, Before, work, After, After1" 
  end

  it "should stack overrides for a list of modules" do
    worker = Worker.new.with WorkerTracer, WorkerTracer1
    worker.work.should == "Before1, Before, work, After, After1" 
  end

  it "should stack overrides for an array of modules" do
    worker = Worker.new.with [WorkerTracer, WorkerTracer1]
    worker.work.should == "Before1, Before, work, After, After1" 
  end
end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;You should carefully consider the warning about monkeypatching &lt;code&gt;Object&lt;/code&gt;!  Also, note that &lt;code&gt;Module.append_features&lt;/code&gt; is actually private, so I had to use &lt;code&gt;m.send :append_features, ...&lt;/code&gt; instead.&lt;/p&gt;


	&lt;p&gt;The syntax is reasonably intuitive and it eliminates the need for an explicit subclass. You can pass a single module, or a list or array of them. Because &lt;code&gt;with&lt;/code&gt; returns the object, you can also chain &lt;code&gt;with&lt;/code&gt; calls.&lt;/p&gt;


	&lt;p&gt;A final note; many developers steer clear of metaprogramming and reflection features in their languages, out of fear. While prudence is &lt;em&gt;definitely&lt;/em&gt; wise, the power of these tools can dramatically accelerate your productivity. &lt;em&gt;Metaprogramming is just programming.&lt;/em&gt; Every developer should master it.&lt;/p&gt;</description>
      <pubDate>Mon, 29 Sep 2008 22:41:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:b54295c4-67e0-4acb-a9f6-ea098a3a29e2</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/09/29/a-scala-style-_with_-construct-for-ruby</link>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>Ruby</category>
      <category>Scala</category>
      <category>with</category>
      <category>mixins</category>
      <category>design</category>
      <category>Metaprogramming</category>
    </item>
    <item>
      <title>Traits vs. Aspects in Scala</title>
      <description>&lt;p&gt;Scala &lt;em&gt;traits&lt;/em&gt; provide a mixin composition mechanism that has been missing in Java. Roughly speaking, you can think of &lt;em&gt;traits&lt;/em&gt; as analogous to Java interfaces, but with implementations.&lt;/p&gt;


	&lt;p&gt;&lt;em&gt;Aspects&lt;/em&gt;, &lt;em&gt;e.g.,&lt;/em&gt; those written in &lt;a href="http://aspectj.org"&gt;AspectJ&lt;/a&gt;, are another mechanism for mixin composition in Java. How do &lt;em&gt;aspects&lt;/em&gt; and &lt;em&gt;traits&lt;/em&gt; compare?&lt;/p&gt;


	&lt;p&gt;Let&amp;#8217;s look at an example trait first, then re-implement the same behavior using an AspectJ aspect, and finally compare the two approaches.&lt;/p&gt;


	&lt;h3&gt;Observing with Traits&lt;/h3&gt;


	&lt;p&gt;In a previous &lt;a href="http://blog.objectmentor.com/articles/2008/08/14/the-seductions-of-scala-part-iii-concurrent-programming"&gt;post on Scala&lt;/a&gt;, I gave an example of the &lt;em&gt;Observer Pattern&lt;/em&gt; implemented using a trait. Chris Shorrock and &lt;a href="http://james-iry.blogspot.com/"&gt;James Iry&lt;/a&gt; provided improved versions in the comments. I&amp;#8217;ll use James&amp;#8217; example here.&lt;/p&gt;


	&lt;p&gt;To keep things as simple as possible, let&amp;#8217;s observe a simple &lt;code&gt;Counter&lt;/code&gt;, which increments an internal count variable by the number input to an &lt;code&gt;add&lt;/code&gt; method.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

class Counter {
    var count = 0
    def add(i: Int) = count += i
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;count&lt;/code&gt; field is actually public, but I will only write to it through &lt;code&gt;add&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;Here is James&amp;#8217; &lt;em&gt;Subject&lt;/em&gt; trait that implements the &lt;em&gt;Observer Pattern&lt;/em&gt;.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

trait Subject {
  type Observer = { def receiveUpdate(subject:Any) }

  private var observers = List[Observer]()
  def addObserver(observer:Observer) = observers ::= observer
  def notifyObservers = observers foreach (_.receiveUpdate(this))
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Effectively, this says that we can use any object as an &lt;code&gt;Observer&lt;/code&gt; as long as it matches the &lt;em&gt;structural type&lt;/em&gt; &lt;code&gt;{ def receiveUpdate(subject:Any) }&lt;/code&gt;. Think of structural types as anonymous interfaces. Here, a valid observer is one that has a &lt;code&gt;receiveUpdate&lt;/code&gt; method taking an argument of &lt;code&gt;Any&lt;/code&gt; type.&lt;/p&gt;


	&lt;p&gt;The rest of the trait manages a list of observers and defines a &lt;code&gt;notifyObservers&lt;/code&gt; method. The expression &lt;code&gt;observers ::= observer&lt;/code&gt; uses the &lt;code&gt;List&lt;/code&gt; &lt;code&gt;::&lt;/code&gt; (&amp;#8220;cons&amp;#8221;) operator to &lt;em&gt;prepend&lt;/em&gt; an item to the list. (Note, I am using the default immutable &lt;code&gt;List&lt;/code&gt;, so a new copy is created everytime.)&lt;/p&gt;


	&lt;p&gt;The &lt;code&gt;notifyObservers&lt;/code&gt; method iterates through the observers, calling &lt;code&gt;receiveUpdate&lt;/code&gt; on each one. The &lt;code&gt;_&lt;/code&gt; that gets replaced with each observer during the iteration.&lt;/p&gt;


	&lt;p&gt;Finally, here is a &lt;a href="http://code.google.com/p/specs"&gt;specs&lt;/a&gt; file that exercises the code.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

import org.specs._

object CounterObserverSpec extends Specification {
    "A Counter Observer" should {
        "observe counter increments" in {
            class CounterObserver {
                var updates = 0
                def receiveUpdate(subject:Any) = updates += 1
            }
            class WatchedCounter extends Counter with Subject {
                override def add(i: Int) = { 
                    super.add(i)
                    notifyObservers
                }
            }
            var watchedCounter = new WatchedCounter
            var counterObserver = new CounterObserver
            watchedCounter.addObserver(counterObserver)
            for (i &amp;lt;- 1 to 3) watchedCounter.add(i)
            counterObserver.updates must_== 3
            watchedCounter.count must_== 6
    }
  }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;em&gt;specs&lt;/em&gt; library is a &lt;span class="caps"&gt;BDD&lt;/span&gt; tool inspired by &lt;a href="http://rspec.info"&gt;rspec&lt;/a&gt; in Rubyland.&lt;/p&gt;


	&lt;p&gt;I won&amp;#8217;t discuss it all the specs-specific details here, but hopefully you&amp;#8217;ll get the general idea of what it&amp;#8217;s doing.&lt;/p&gt;


	&lt;p&gt;Inside the &lt;code&gt;"observe counter increments" in {...}&lt;/code&gt;, I start by declaring two classes, &lt;code&gt;CounterObserver&lt;/code&gt; and &lt;code&gt;WatchedCounter&lt;/code&gt;. &lt;code&gt;CounterObserver&lt;/code&gt; satisfies our required &lt;em&gt;structural type&lt;/em&gt;, &lt;em&gt;i.e.,&lt;/em&gt; it provides a &lt;code&gt;receiveUpdate&lt;/code&gt; method.&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;WatchedCounter&lt;/code&gt; subclasses &lt;code&gt;Counter&lt;/code&gt; and mixes in the &lt;code&gt;Subject&lt;/code&gt; trait. It overrides the &lt;code&gt;add&lt;/code&gt; method, where it calls &lt;code&gt;Counter&lt;/code&gt;&amp;#8217;s &lt;code&gt;add&lt;/code&gt; first, then notifies the observers. No parentheses are used in the invocation of &lt;code&gt;notifyObservers&lt;/code&gt; because the method was not defined to take any!&lt;/p&gt;


	&lt;p&gt;Next, I create an instance of each class, add the observer to the &lt;code&gt;WatchedCounter&lt;/code&gt;, and make 3 calls to &lt;code&gt;watchedCounter.add&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;Finally, I use the &amp;#8220;&lt;code&gt;actual must_== expected&lt;/code&gt;&amp;#8221; idiom to test the results. The observer should have seen 3 updates, while the counter should have a total of 6.&lt;/p&gt;


	&lt;p&gt;The following simple bash shell script will build and run the code.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
SCALA_HOME=...
SCALA_SPECS_HOME=...
CP=$SCALA_HOME/lib/scala-library.jar:$SCALA_SPECS_HOME/specs-1.3.1.jar:bin
rm -rf bin
mkdir -p bin
scalac -d bin -cp $CP src/example/*.scala
scala -cp $CP example/CounterObserverSpec
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note that I put all the sources in a &lt;code&gt;src/example&lt;/code&gt; directory. Also, I&amp;#8217;m using v1.3.1 of &lt;em&gt;specs&lt;/em&gt;, as well as v2.7.1 of Scala. You should get the following output.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
Specification "CounterObserverSpec" 
  A Counter Observer should
  + observe counter increments

Total for specification "CounterObserverSpec":
Finished in 0 second, 60 ms
1 example, 2 assertions, 0 failure, 0 error
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;h3&gt;Observing with Aspects&lt;/h3&gt;


	&lt;p&gt;Because Scala compiles to Java byte code, I can use AspectJ to advice Scala code! For this to work, you have to be aware of how Scala represents its concepts in byte code. For example, object declarations, &lt;em&gt;e.g.,&lt;/em&gt; &lt;code&gt;object Foo {...}&lt;/code&gt; become static final classes. Also, method names like &lt;code&gt;+&lt;/code&gt; become &lt;code&gt;$plus&lt;/code&gt; in byte code.&lt;/p&gt;


	&lt;p&gt;However, most Scala type, method, and variable names can be used as is in AspectJ. This is true for my example.&lt;/p&gt;


	&lt;p&gt;Here is an aspect that observes calls to &lt;code&gt;Counter.add&lt;/code&gt;.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

public aspect CounterObserver {
    after(Object counter, int value): 
        call(void *.add(int)) &amp;#38;&amp;#38; target(counter) &amp;#38;&amp;#38; args(value) {

        RecordedObservations.record("adding "+value);
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;You can read this aspect as follows, &lt;em&gt;after calling &lt;code&gt;Counter.add&lt;/code&gt; (and keeping track of the Counter object that was called, and the value passed to the method), call the static method &lt;code&gt;record&lt;/code&gt; on the &lt;code&gt;RecordedObservations&lt;/code&gt;.&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;m using a separate Scala object &lt;code&gt;RecordedObservations&lt;/code&gt;&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

object RecordedObservations {
    private var messages = List[String]()
    def record(message: String):Unit = messages ::= message
    def count() = messages.length
    def reset():Unit = messages = Nil
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Recall that this is effectively a static final Java class. I need this separate object, rather than keeping information in the aspect itself, because of the simple-minded way I&amp;#8217;m building the code. ;) However, it&amp;#8217;s generally a good idea with aspects to delegate most of the work to Java or Scala code anyway.&lt;/p&gt;


	&lt;p&gt;Now, the &amp;#8220;spec&amp;#8221; file is:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

import org.specs._

object CounterObserverSpec extends Specification {
    "A Counter Observer" should {
        "observe counter increments" in {
            RecordedObservations.reset()
            var counter = new Counter
            for (i &amp;lt;- 1 to 3) counter.add(i)
            RecordedObservations.count() must_== 3
            counter.count must_== 6
    }
  }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;This time, I don&amp;#8217;t need two more classes for the adding a mixin trait or defining an observer. Also, I call &lt;code&gt;RecordedObservations.count&lt;/code&gt; to ensure it was called 3 times.&lt;/p&gt;


	&lt;p&gt;The build script is also slightly different to add the AspectJ compilation.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
SCALA_HOME=...
SCALA_SPECS_HOME=...
ASPECTJ_HOME=...
CP=$SCALA_HOME/lib/scala-library.jar:$SCALA_SPECS_HOME/specs-1.3.1.jar:$ASPECTJ_HOME/lib/aspectjrt.jar:bin
rm -rf bin app.jar
mkdir -p bin
scalac -d bin -cp $CP src/example/*.scala 
ajc -1.5 -outjar app.jar -cp $CP -inpath bin src/example/CounterObserver.aj
aj -cp $ASPECTJ_HOME/lib/aspectjweaver.jar:app.jar:$CP example.CounterObserverSpec
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;ajc&lt;/code&gt; command not only compiles the aspect, but it &amp;#8220;weaves&amp;#8221; into the compiled Scala classes in the &lt;code&gt;bin&lt;/code&gt; directory. Actually, it only affects the &lt;code&gt;Counter&lt;/code&gt; class. Then it writes all the woven and unmodified class files to &lt;code&gt;app.jar&lt;/code&gt;, which is used to execute the test. Note that for production use, you might prefer &lt;a href="http://www.eclipse.org/aspectj/doc/released/devguide/ltw.html"&gt;load-time weaving&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;The output is the same as before (except for the milliseconds), so I won&amp;#8217;t show it here.&lt;/p&gt;


	&lt;h3&gt;Comparing Traits with Aspects&lt;/h3&gt;


	&lt;p&gt;So far, both approaches are equally viable. The traits approach obviously doesn&amp;#8217;t require a separate language and corresponding tool set.&lt;/p&gt;


	&lt;p&gt;However, traits have one important limitation with respect to aspects. Aspects let you define &lt;em&gt;pointcuts&lt;/em&gt; that are queries over all possible points where new behavior or modifications might be desired. These points are called &lt;em&gt;join points&lt;/em&gt; in aspect terminology. The aspect I showed above has a simple pointcut that selects one join point, calls to the &lt;code&gt;Counter.add&lt;/code&gt; method.&lt;/p&gt;


	&lt;p&gt;However, what if I wanted to observe all state changes in all classes in a package? Defining traits for each case would be tedious and error prone, since it would be easy to overlook some cases. With an aspect framework like AspectJ, I can implement observation at all the points I care about in a &lt;em&gt;modular&lt;/em&gt; way.&lt;/p&gt;


	&lt;p&gt;Aspect frameworks support this by providing wildcard mechanisms. I won&amp;#8217;t go into the details here, but the &lt;code&gt;*&lt;/code&gt; in the previous aspect is an example, matching any type. Also, one of the most powerful techniques for writing robust aspects is to use pointcuts that reference only annotations, a form of abstraction. As a final example, if I add an annotation &lt;code&gt;Adder&lt;/code&gt; to &lt;code&gt;Counter.add&lt;/code&gt;,&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

class Counter {
    var count = 0
    @Adder def add(i: Int) = count += i
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Then I can rewrite the aspect as follows.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
package example

public aspect CounterObserver {
    after(Object counter, int value): 
        call(@Adder void *.*(int)) &amp;#38;&amp;#38; target(counter) &amp;#38;&amp;#38; args(value) {

        RecordedObservations.record("adding "+value);
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Now, there are no type and method names in the pointcut. Any instance method on any visible type that takes one &lt;code&gt;int&lt;/code&gt; (or Scala &lt;code&gt;Int&lt;/code&gt;) argument and is annotated with &lt;code&gt;Adder&lt;/code&gt; will get matched.&lt;/p&gt;


	&lt;p&gt;Note: Scala requires that you create any custom annotations as normal Java annotations. Also, if you intend to use them with Aspects, use runtime retention policy, which will be necessary if you use &lt;a href="http://www.eclipse.org/aspectj/doc/released/devguide/ltw.html"&gt;load-time weaving&lt;/a&gt;.&lt;/p&gt;


	&lt;h3&gt;Conclusion&lt;/h3&gt;


	&lt;p&gt;If you need to mix in behavior in a specific, relatively-localized set of classes, Scala traits are probably all you need and you don&amp;#8217;t need another language. If you need more &amp;#8220;pervasive&amp;#8221; modifications (&lt;em&gt;e.g.,&lt;/em&gt; tracing, policy enforcement, security), consider using aspects.&lt;/p&gt;


	&lt;h4&gt;Acknowledgements&lt;/h4&gt;


	&lt;p&gt;Thanks to Ramnivas Laddad, whose forthcoming 2&lt;sup&gt;nd&lt;/sup&gt; Edition of &lt;cite&gt;AspectJ in Action&lt;/cite&gt; got me thinking about this topic.&lt;/p&gt;</description>
      <pubDate>Sat, 27 Sep 2008 22:33:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:8628eb5f-f195-4ebe-a10a-f3ee9d66d591</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/09/27/traits-vs-aspects-in-scala</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>Scala</category>
      <category>aspects</category>
      <category>AspectJ</category>
      <category>mixins</category>
    </item>
    <item>
      <title>The Liskov Substitution Principle for &amp;quot;Duck-Typed&amp;quot; Languages</title>
      <description>&lt;p&gt;&lt;span class="caps"&gt;OCP&lt;/span&gt; and &lt;span class="caps"&gt;LSP&lt;/span&gt; together tell us how to organize similar &lt;em&gt;vs.&lt;/em&gt; variant behaviors. I blogged the other day about &lt;a href="http://blog.objectmentor.com/articles/2008/09/04/the-open-closed-principle-for-languages-with-open-classes"&gt;&lt;span class="caps"&gt;OCP&lt;/span&gt; in the context of languages with open classes&lt;/a&gt;
 (&lt;em&gt;i.e.,&lt;/em&gt; dynamically-typed languages). Let&amp;#8217;s look at the &lt;a href="http://www.objectmentor.com/resources/articles/lsp.pdf"&gt;Liskov Substitution Principle&lt;/a&gt; (LSP).&lt;/p&gt;


	&lt;p&gt;The Liskov Substitution Principle was coined by Barbara Liskov in &lt;a href="http://portal.acm.org/citation.cfm?id=62141"&gt;Data Abstraction and Hierarchy&lt;/a&gt; (1987).&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2, then S is a subtype of T.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;I&amp;#8217;ve always liked the elegant simplicity, yet power, of &lt;span class="caps"&gt;LSP&lt;/span&gt;. In less formal terms, it says that if a client (program) expects objects of one type to behave in a certain way, then it&amp;#8217;s only okay to substitute objects of another type if the same expectations are satisfied.&lt;/p&gt;


	&lt;p&gt;This is our best definition of inheritance. The well-known &lt;strong&gt;is-a&lt;/strong&gt; relationship between types is not precise enough. Rather, the relationship has to be &lt;strong&gt;behaves-as-a&lt;/strong&gt;, which unfortunately is more of a mouthful. Note that &lt;strong&gt;is-a&lt;/strong&gt; focuses on the &lt;em&gt;structural&lt;/em&gt; relationship, while &lt;strong&gt;behaves-as-a&lt;/strong&gt; focuses on the &lt;em&gt;behavioral&lt;/em&gt; relationship. A very useful, pre-TDD design technique called &lt;a href="http://en.wikipedia.org/wiki/Design_by_contract"&gt;Design by Contract&lt;/a&gt; emerges out of &lt;span class="caps"&gt;LSP&lt;/span&gt;, but that&amp;#8217;s another topic.&lt;/p&gt;


	&lt;p&gt;Note that there is a slight assumption that I made in the previous paragraph. I said that &lt;span class="caps"&gt;LSP&lt;/span&gt; defines &lt;em&gt;inheritance&lt;/em&gt;. Why inheritance specifically and not &lt;em&gt;substitutability&lt;/em&gt;, in general? Well, inheritance has been the main vehicle for substitutability for most OO languages, especially the statically-typed ones.&lt;/p&gt;


	&lt;p&gt;For example, a Java application might use a simple tracing abstraction like this.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
public interface Tracing {
    void trace(String message);
}
    &lt;/code&gt;
&lt;/pre&gt;  

	&lt;p&gt;Clients might use this to trace methods calls to a log. Only classes that implement the &lt;code&gt;Tracer&lt;/code&gt; interface can be given to these clients. For example,&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
public class TracerClient {
    private Tracer tracer;

    public TracerClient(Tracer tracer) {
        this.tracer = tracer;
    }

    public void doWork() {
        tracer.trace("in doWork():");
        // ...
    }
}
    &lt;/code&gt;
&lt;/pre&gt;  

	&lt;p&gt;However, &lt;a href="http://en.wikipedia.org/wiki/Duck_typing"&gt;Duck Typing&lt;/a&gt; is another form of substitutability that is commonly seen in dynamically-typed languages, like Ruby and Python.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;If it walks like a duck and quacks like a duck, it must be a duck.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;Informally, duck typing says that a client can use any object you give it as long as the object implements the methods the client wants to invoke on it. Put another way, the object must respond to the messages the client wants to send to it.&lt;/p&gt;


	&lt;p&gt;The object appears to be a &amp;#8220;duck&amp;#8221; as far as the client is concerned.&lt;/p&gt;


	&lt;p&gt;In or example, clients only care about the &lt;code&gt;trace(message)&lt;/code&gt; method being supported. So, we might do the following in Ruby.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class TracerClient 
  def initialize tracer 
    @tracer = tracer
  end

  def do_work
    @tracer.trace "in do_work:" 
    # ... 
  end
end

class MyTracer
  def trace message
    p message
  end
end

client = TracerClient.new(MyTracer.new)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;No &amp;#8220;interface&amp;#8221; is necessary. I just need to pass an object to &lt;code&gt;TracerClient.initialize&lt;/code&gt; that responds to the &lt;code&gt;trace&lt;/code&gt; message. Here, I defined a class for the purpose. You could also add the &lt;code&gt;trace&lt;/code&gt; method to another type or object.&lt;/p&gt;


	&lt;p&gt;So, &lt;span class="caps"&gt;LSP&lt;/span&gt; is still essential, in the generic sense of valid substitutability, but it doesn&amp;#8217;t have to be inheritance based.&lt;/p&gt;


	&lt;p&gt;Is Duck Typing good or bad? It largely comes down to your view about dynamically-typed &lt;em&gt;vs.&lt;/em&gt; statically-typed languages. I don&amp;#8217;t want to get into that debate here! However, I&amp;#8217;ll make a few remarks.&lt;/p&gt;


	&lt;p&gt;On the negative side, without a &lt;code&gt;Tracer&lt;/code&gt; abstraction, you have to rely on appropriate naming of objects to convey what they do (but you should be doing that anyway). Also, it&amp;#8217;s harder to find all the &amp;#8220;tracing-behaving&amp;#8221; objects in the system.&lt;/p&gt;


	&lt;p&gt;On the other hand, the client really doesn&amp;#8217;t care about a &amp;#8220;Tracer&amp;#8221; type, only a single method. So, we&amp;#8217;ve decoupled &amp;#8220;client&amp;#8221; and &amp;#8220;server&amp;#8221; just a bit more. This decoupling is more evident when using closures to express behavior, &lt;em&gt;e.g.,&lt;/em&gt; for &lt;code&gt;Enumerable&lt;/code&gt; methods. In our case, we could write the following.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class TracerClient2 
  def initialize &amp;#38;tracer 
    @tracer = tracer
  end

  def do_work 
    @tracer.call "in do_work:" 
    # ... 
  end
end

client = TracerClient2.new {|message| p "block tracer: #{message}"}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;For comparison, consider how we might approach substitutability in &lt;a href="http://www.scala-lang.org/"&gt;Scala&lt;/a&gt;. As a statically-typed language, Scala doesn&amp;#8217;t support duck typing &lt;em&gt;per se&lt;/em&gt;, but it does support a very similar mechanism called &lt;a href="http://neilbartlett.name/blog/2007/09/13/statically-checked-duck-typing-in-scala/"&gt;structural types&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;Essentially, structural types let us declare that a method parameter must support one or more methods, without having to say it supports a full interface. Loosely speaking, it&amp;#8217;s like using an anonymous interface.&lt;/p&gt;


	&lt;p&gt;In our Java example, when we declare a tracer object in our client, we would be able to declare that is supports &lt;code&gt;trace&lt;/code&gt;, without having to specify that it implements a full interface.&lt;/p&gt;


	&lt;p&gt;To be explicit, recall our Java constructor for &lt;code&gt;TestClient&lt;/code&gt;.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
public class TracerClient {
    public TracerClient(Tracer tracer) { ... }
    // ...
    }
}
    &lt;/code&gt;
&lt;/pre&gt;  

In Scala, a complete example would be the following.
&lt;pre&gt;
    &lt;code&gt;
class ScalaTracerClient(val tracer: { def trace(message:String) }) {
    def doWork() = { tracer.trace("doWork") }
}

class ScalaTracer() {
    def trace(message: String) = { println("Scala: "+message) }
}

object TestScalaTracerClient {
    def main() {
        val client = new ScalaTracerClient(new ScalaTracer())
        client.doWork();
    }
}
TestScalaTracerClient.main()
    &lt;/code&gt;
&lt;/pre&gt;  

	&lt;p&gt;Recall from &lt;a href="http://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i"&gt;my previous blogs on Scala&lt;/a&gt;, the argument list to the class name is the constructor arguments. The constructor takes a &lt;code&gt;tracer&lt;/code&gt; argument whose &amp;#8220;type&amp;#8221; (after the &amp;#8217;:&amp;#8217;) is &lt;code&gt;{ def trace(message:String) }&lt;/code&gt;. That is, all we require of &lt;code&gt;tracer&lt;/code&gt; is that it support the &lt;code&gt;trace&lt;/code&gt; method.&lt;/p&gt;


	&lt;p&gt;So, we get duck type-like behavior, but statically type checked. We&amp;#8217;ll get a compile error, rather than a run-time error, if someone passes an object to the client that doesn&amp;#8217;t respond to &lt;code&gt;tracer&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;To conclude, &lt;span class="caps"&gt;LSP&lt;/span&gt; can be reworded &lt;em&gt;very&lt;/em&gt; slightly.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2, then S is &lt;strong&gt;substitutable for&lt;/strong&gt; T.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;I replaced &lt;strong&gt;a subtype of&lt;/strong&gt; with &lt;strong&gt;substitutable for&lt;/strong&gt;.&lt;/p&gt;


	&lt;p&gt;An important point is that the idea of a &amp;#8220;contract&amp;#8221; between the types and their clients is still important, even in a  language with duck-typing or structural typing. However, languages with these features give us more ways to extend our system, while still supporting &lt;span class="caps"&gt;LSP&lt;/span&gt;.&lt;/p&gt;</description>
      <pubDate>Sat, 06 Sep 2008 23:48:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:48d425c0-b536-44de-bf6a-b83755c064b9</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/09/06/the-liskov-substitution-principle-for-duck-typed-languages</link>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>Design Principles</category>
      <category>Ruby</category>
      <category>ducktyping</category>
      <category>Scala</category>
      <category>Java</category>
      <category>design</category>
      <category>LSP</category>
    </item>
    <item>
      <title>The Seductions of Scala, Part III - Concurrent Programming</title>
      <description>&lt;p&gt;This is my third and last blog entry on &lt;em&gt;The Seductions of Scala&lt;/em&gt;, where we&amp;#8217;ll look at concurrency using &lt;code&gt;Actors&lt;/code&gt; and draw some final conclusions.&lt;/p&gt;


	&lt;h2&gt;Writing Robust, Concurrent Programs with Scala&lt;/h2&gt;


	&lt;p&gt;The most commonly used model of concurrency in imperative languages (and databases) uses shared, mutable state with access synchronization. (Recall that synchronization isn&amp;#8217;t necessary for reading immutable objects.)&lt;/p&gt;


	&lt;p&gt;However, it&amp;#8217;s widely known that this kind of concurrency programming is very difficult to do properly and few programmers are skilled enough to write such programs.&lt;/p&gt;


	&lt;p&gt;Because pure functional languages have no side effects and no shared, mutable state, there is nothing to synchronize. This is the main reason for the resurgent interest in function programming recently, as a potential solution to the so-called &lt;a href="http://www.technologyreview.com/Infotech/17682/page1/"&gt;multicore problem&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;Instead, most functional languages, in particular, &lt;a href="http://www.erlang.org"&gt;Erlang&lt;/a&gt; and Scala, use the &lt;a href="http://en.wikipedia.org/wiki/Actor_model"&gt;Actor model of concurrency&lt;/a&gt;, where autonomous &amp;#8220;objects&amp;#8221; run in separate processes or threads and they pass messages back and forth to communicate. The simplicity of the Actor model makes it far easier to create robust programs. Erlang processes are so lightweight that it is common for server-side applications to have thousands of communicating processes.&lt;/p&gt;


	&lt;h3&gt;Actors in Scala&lt;/h3&gt;


	&lt;p&gt;Let&amp;#8217;s finish our survey of Scala with an example using Scala&amp;#8217;s Actors library.&lt;/p&gt;


	&lt;p&gt;Here&amp;#8217;s a simple Actor that just counts to 10, printing each number, one per second.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
import scala.actors._
object CountingActor extends Actor { 
    def act() { 
        for (i &amp;lt;- 1 to 10) { 
            println("Number: "+i)
            Thread.sleep(1000) 
        } 
    } 
} 

CountingActor.start()
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The last line starts the actor, which implicitly invokes the &lt;code&gt;act&lt;/code&gt; method. This actor does not respond to any messages from other actors.&lt;/p&gt;


	&lt;p&gt;Here is an actor that responds to messages, echoing the message it receives.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
import scala.actors.Actor._ 
val echoActor = actor {
    while (true) {
        receive {
            case msg =&amp;gt; println("received: "+msg)
        }
    }
}
echoActor ! "hello" 
echoActor ! "world!" 
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;In this case, we do the equivalent of a Java &amp;#8220;static import&amp;#8221; of the methods on &lt;code&gt;Actor&lt;/code&gt;, &lt;em&gt;e.g.,&lt;/em&gt; &lt;code&gt;actor&lt;/code&gt;. Also, we don&amp;#8217;t actually need a special class, we can just create an object with the desired behavior. This object has an infinite loop that effectively blocks while waiting for an incoming message. The &lt;code&gt;receive&lt;/code&gt; method gets a block that is a match statement, which matches on &lt;em&gt;anything&lt;/em&gt; received and prints it out.&lt;/p&gt;


	&lt;p&gt;Messages are sent using the &lt;code&gt;target_actor ! message&lt;/code&gt; syntax.&lt;/p&gt;


	&lt;p&gt;As a final example, let&amp;#8217;s do something non-trivial; a contrived network node monitor.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
import scala.actors._
import scala.actors.Actor._
import java.net.InetAddress 
import java.io.IOException

case class NodeStatusRequest(address: InetAddress, respondTo: Actor) 

sealed abstract class NodeStatus
case class Available(address: InetAddress) extends NodeStatus
case class Unresponsive(address: InetAddress, reason: Option[String]) extends NodeStatus

object NetworkMonitor extends Actor {
    def act() {
        loop {
            react {  // Like receive, but uses thread polling for efficiency.
                case NodeStatusRequest(address, actor) =&amp;gt; 
                    actor ! checkNodeStatus(address)
                case "EXIT" =&amp;gt; exit()
            }
        }
    }
    val timeoutInMillis = 1000;
    def checkNodeStatus(address: InetAddress) = {
        try {
            if (address.isReachable(timeoutInMillis)) 
                Available(address)
            else
                Unresponsive(address, None)
        } catch {
            case ex: IOException =&amp;gt; 
                Unresponsive(address, Some("IOException thrown: "+ex.getMessage()))
        }
    }
}

// Try it out:

val allOnes = Array(1, 1, 1, 1).map(_.toByte)
NetworkMonitor.start()
NetworkMonitor ! NodeStatusRequest(InetAddress.getByName("www.scala-lang.org"), self)
NetworkMonitor ! NodeStatusRequest(InetAddress.getByAddress("localhost", allOnes), self)
NetworkMonitor ! NodeStatusRequest(InetAddress.getByName("www.objectmentor.com"), self)
NetworkMonitor ! "EXIT" 
self ! "No one expects the Spanish Inquisition!!" 

def handleNodeStatusResponse(response: NodeStatus) = response match {
    // Sealed classes help here
    case Available(address) =&amp;gt; 
        println("Node "+address+" is alive.")
    case Unresponsive(address, None) =&amp;gt; 
        println("Node "+address+" is unavailable. Reason: &amp;lt;unknown&amp;gt;")
    case Unresponsive(address, Some(reason)) =&amp;gt; 
        println("Node "+address+" is unavailable. Reason: "+reason)
}

for (i &amp;lt;- 1 to 4) self.receive {   // Sealed classes don't help here
    case (response: NodeStatus) =&amp;gt; handleNodeStatusResponse(response)
    case unexpected =&amp;gt; println("Unexpected response: "+unexpected)
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;We begin by importing the &lt;code&gt;Actor&lt;/code&gt; classes, the methods on &lt;code&gt;Actor&lt;/code&gt;, like &lt;code&gt;actor&lt;/code&gt;, and a few Java classes we need.&lt;/p&gt;


	&lt;p&gt;Next we define a &lt;em&gt;sealed&lt;/em&gt; abstract base class. The &lt;code&gt;sealed&lt;/code&gt; keyword tells the compiler that the only subclasses will be defined in this file. This is useful for the case statements that use them. The compiler will know that it doesn&amp;#8217;t have to worry about potential cases that aren&amp;#8217;t covered, if new &lt;code&gt;NodeStatus&lt;/code&gt; subclasses are created. Otherwise, we would have to add a default case clause (&lt;em&gt;e.g.,&lt;/em&gt; &lt;code&gt;case _ =&amp;gt; ...&lt;/code&gt;) to prevent warnings (and possible errors!) about not matching an input. Sealed class hierarchies are a useful feature for robustness (but watch for potential Open/Closed Principle violations!).&lt;/p&gt;


	&lt;p&gt;The sealed class hierarchy encapsulates all the possible node status values (somewhat contrived for the example). The node is either &lt;code&gt;Available&lt;/code&gt; or &lt;code&gt;Unresponsive&lt;/code&gt;. If &lt;code&gt;Unresponsive&lt;/code&gt;, an optional &lt;code&gt;reason&lt;/code&gt; message is returned.&lt;/p&gt;


	&lt;p&gt;Note that we only get the benefit of sealed classes here because we match on them in the &lt;code&gt;handleNodeStatusResponse&lt;/code&gt; message, which requires a &lt;code&gt;response&lt;/code&gt; argument of type &lt;code&gt;NodeStatus&lt;/code&gt;. In contrast, the &lt;code&gt;receive&lt;/code&gt; method effectively takes an &lt;code&gt;Any&lt;/code&gt; argument, so sealed classes don&amp;#8217;t help on the line with the comment &amp;#8220;Sealed classes don&amp;#8217;t help here&amp;#8221;. In that case, we really need a default, the &lt;code&gt;case unexpected =&amp;gt; ...&lt;/code&gt; clause. (I added the message &lt;code&gt;self ! "No one expects the Spanish Inquisition!!"&lt;/code&gt; to test this default handler.)&lt;/p&gt;


	&lt;p&gt;In the first draft of this blog post, I didn&amp;#8217;t know these details about sealed classes. I used a simpler implementation that couldn&amp;#8217;t benefit from sealed classes. Thanks to the first commenter, LaLit Pant, who corrected my mistake!&lt;/p&gt;


	&lt;p&gt;The &lt;code&gt;NetworkMonitor&lt;/code&gt; loops, waiting for a &lt;code&gt;NodeStatusRequest&lt;/code&gt; or the special string &amp;#8220;EXIT&amp;#8221;, which tells it to quit. Note that the actor sending the request passes itself, so the monitor can reply to it.&lt;/p&gt;


	&lt;p&gt;The &lt;code&gt;checkNodeStatus&lt;/code&gt; attempts to contact the node, with a 1 second timeout. It returns an appropriate &lt;code&gt;NodeStatus&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;Then we try it out with three addresses. Note that we pass &lt;code&gt;self&lt;/code&gt; as the requesting actor. This is an &lt;code&gt;Actor&lt;/code&gt; wrapping the current thread, imported from &lt;code&gt;Actor&lt;/code&gt;. It is analogous to Java&amp;#8217;s &lt;code&gt;Thread.currentThread()&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;Curiously enough, when I run this code, I get the following results.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
Unexpected response: No one expects the Spanish Inquisition!!
Node www.scala-lang.org/128.178.154.102 is unavailable. Reason: &amp;lt;unknown&amp;gt;
Node localhost/1.1.1.1 is unavailable. Reason: &amp;lt;unknown&amp;gt;
Node www.objectmentor.com/206.191.6.12 is alive.
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The message about the Spanish Inquisition was sent last, but processed first, probably because &lt;code&gt;self&lt;/code&gt; sent it to itself.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;m not sure why www.scala-lang.org couldn&amp;#8217;t be reached. A longer timeout didn&amp;#8217;t help. According to the Javadocs for &lt;a href="http://java.sun.com/javase/6/docs/api/java/net/InetAddress.html#isReachable(int"&gt;InetAddress.isReachable&lt;/a&gt;), it uses &lt;span class="caps"&gt;ICMP ECHO&lt;/span&gt; REQUESTs if the privilege can be obtained, otherwise it tries to establish a &lt;span class="caps"&gt;TCP&lt;/span&gt; connection on port 7 (Echo) of the destination host. Perhaps neither is supported on the scala-lang.org site.&lt;/p&gt;


	&lt;h2&gt;Conclusions&lt;/h2&gt;


	&lt;p&gt;Here are some concluding observations about Scala &lt;em&gt;vis-&#224;-vis&lt;/em&gt; Java and other options.&lt;/p&gt;


	&lt;h3&gt;A Better Java&lt;/h3&gt;


	&lt;p&gt;Ignoring the functional programming aspects for a moment, I think Scala improves on Java in a number of very useful ways, including:&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;&lt;strong&gt;A more succinct syntax.&lt;/strong&gt; There&amp;#8217;s far less boilerplate, like for fields and their accessors. Type inference and optional semicolons, curly braces, &lt;em&gt;etc.&lt;/em&gt; also reduce &amp;#8220;noise&amp;#8221;.&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;A true &lt;em&gt;mixin&lt;/em&gt; model.&lt;/strong&gt; The addition of &lt;em&gt;traits&lt;/em&gt; solves the problem of not having a good &lt;a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself"&gt;&lt;span class="caps"&gt;DRY&lt;/span&gt;&lt;/a&gt; way to mix in additional functionality declared by Java interfaces.&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;More flexible method names and invocation syntax.&lt;/strong&gt; Java took away operator overloading; Scala gives it back, as well as other benefits of using non-alphanumeric characters in method names. (Ruby programmers enjoy writing &lt;code&gt;list.empty?&lt;/code&gt;, for example.) &lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Tuples.&lt;/strong&gt; A personal favorite, I&amp;#8217;ve always wanted the ability to return multiple values from a method, without having to create an &lt;em&gt;ad hoc&lt;/em&gt; class to hold the values.&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Better separation of mutable &lt;em&gt;vs.&lt;/em&gt; immutable objects.&lt;/strong&gt; While Java provides some ability to make objects &lt;code&gt;final&lt;/code&gt;, Scala makes the distinction between mutability and immutability more explicit and encourages the latter as a more robust programming style.&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;First-class functions and closures.&lt;/strong&gt; Okay, these last two points are really about FP, but they sure help in OO code, too!&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Better mechanisms for avoiding &lt;code&gt;null&lt;/code&gt;&amp;#8217;s.&lt;/strong&gt; The &lt;code&gt;Option&lt;/code&gt; type makes code more robust than allowing &lt;code&gt;null&lt;/code&gt; values.&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Interoperability with Java libraries.&lt;/strong&gt; Scala compiles to byte code so adding Scala code to existing
Java applications is about as seamless as possible.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;So, even if you don&amp;#8217;t believe in FP, you will gain a lot just by using Scala as a better Java.&lt;/p&gt;


	&lt;h3&gt;Functional Programming&lt;/h3&gt;


	&lt;p&gt;&lt;strong&gt;But&lt;/strong&gt;, you shouldn&amp;#8217;t ignore the benefits of FP!&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;&lt;strong&gt;Better robustness.&lt;/strong&gt; Not only for concurrent programs, but using immutable objects (a.k.a. &lt;em&gt;value objects&lt;/em&gt;) reduces the potential for bugs.&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;A workable concurrency model.&lt;/strong&gt; I use the term &lt;em&gt;workable&lt;/em&gt; because so few developers can write robust concurrent code using the synchronization on shared state model. Even for those of you who can, why bother when Actors are so much easier??&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Reduced code complexity.&lt;/strong&gt; Functional code tends to be very succinct. I can&amp;#8217;t overestimate the importance of rooting out &lt;strong&gt;all&lt;/strong&gt; &lt;em&gt;accidental&lt;/em&gt; complexity in your code base. Excess complexity is one of the most pervasive detriments to productivity and morale that I see in my clients&amp;#8217; code bases!&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;First-class functions and closures.&lt;/strong&gt; Composition and succinct code are much easier with first-class functions.&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Pattern matching.&lt;/strong&gt; FP-style pattern matching makes &amp;#8220;routing&amp;#8221; of messages and delegation much easier.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;Of course, you can mimic some of these features in pure Java and I encourage you to do so if you aren&amp;#8217;t using Scala.&lt;/p&gt;


	&lt;h3&gt;Static &lt;em&gt;vs.&lt;/em&gt; Dynamic Typing&lt;/h3&gt;


	&lt;p&gt;The debate on the relative merits of static &lt;em&gt;vs.&lt;/em&gt; dynamic typing is outside our scope, but I will make a few personal observations.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;ve been a dedicated &lt;a href="http://www.rubyist.net/~slagell/ruby/"&gt;Rubyist&lt;/a&gt; for a while. It is hard to deny the way that dynamic typing simplifies code and as I said in the previous section, I take code complexity &lt;em&gt;very&lt;/em&gt; seriously.&lt;/p&gt;


	&lt;p&gt;Scala&amp;#8217;s type system and type inference go a long way towards providing the benefits of static typing with the cleaner syntax of dynamic typing, but Scala doesn&amp;#8217;t eliminate the extra complexity of static typing.&lt;/p&gt;


	&lt;p&gt;Recall my Observer example from the &lt;a href="http://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i"&gt;first blog post&lt;/a&gt;, where I used traits to implement it.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
trait Observer[S] {
    def receiveUpdate(subject: S);
}

trait Subject[S] { 
    this: S =&amp;gt;
    private var observers: List[Observer[S]] = Nil
    def addObserver(observer: Observer[S]) = observers = observer :: observers

    def notifyObservers() = observers.foreach(_.receiveUpdate(this))
}
    &lt;/code&gt;
&lt;/pre&gt;

In Ruby, we might implement it this way.
&lt;pre&gt;
    &lt;code&gt;
module Subject 
    def add_observer(observer) 
      @observers ||= []
      @observers &amp;lt;&amp;lt; observer  # append, rather than replace with new array
  end

    def notify_observers
      @observers.each {|o| o.receive_update(self)} if @observers
  end
end
    &lt;/code&gt;
&lt;/pre&gt;        

	&lt;p&gt;There is no need for an &lt;code&gt;Observer&lt;/code&gt; module. As long as every observer responds to the &lt;code&gt;receive_update&lt;/code&gt; &amp;#8220;message&amp;#8221;, we&amp;#8217;re fine.&lt;/p&gt;


	&lt;p&gt;I commented the line where I append to the existing &lt;code&gt;@observers&lt;/code&gt; array, rather than build a new one, which would be the FP and Scala way. Appending to the existing array would be more typical of Ruby code, but this implementation is not as thread safe as an FP-style approach.&lt;/p&gt;


	&lt;p&gt;The trailing &lt;code&gt;if&lt;/code&gt; expression in &lt;code&gt;notify_observers&lt;/code&gt; means that nothing is done if &lt;code&gt;@observers&lt;/code&gt; is still &lt;code&gt;nil&lt;/code&gt;, &lt;em&gt;i.e.,&lt;/em&gt; it was never initialized in &lt;code&gt;add_observer&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;So, which is better? The amount of code is not that different, but it took me significantly longer to write the Scala version. In part, this was due to my novice chops, but the reason it took me so long was because I had to solve a design issue resulting from the static typing. I had to learn about the &lt;em&gt;typed self&lt;/em&gt; construct used in the first line of the &lt;code&gt;Subject&lt;/code&gt; trait. This was the only way to allow the &lt;code&gt;Observer.receiveUpdate&lt;/code&gt; method accept to an argument of type &lt;code&gt;S&lt;/code&gt;, rather than of type &lt;code&gt;Subject[S]&lt;/code&gt;. It was worth it to me to achieve the &amp;#8220;cleaner&amp;#8221; &lt;span class="caps"&gt;API&lt;/span&gt;.&lt;/p&gt;


	&lt;p&gt;Okay, perhaps I&amp;#8217;ll know this next time and spend about the same amount of time implementing a Ruby &lt;em&gt;vs.&lt;/em&gt; Scala version of something. However, I think it&amp;#8217;s notable that sometimes static typing can get in the way of your intentions and goal of achieving clarity. (At other times, the types add useful documentation.) I know this isn&amp;#8217;t the only valid argument you can make, one way or the other, but it&amp;#8217;s one reason that dynamic languages are so appealing.&lt;/p&gt;


	&lt;h3&gt;&lt;em&gt;Poly-paradigm&lt;/em&gt; Languages &lt;em&gt;vs.&lt;/em&gt; Mixing Several Languages&lt;/h3&gt;


	&lt;p&gt;So, you&amp;#8217;re convinced that you should use FP sometimes and &lt;span class="caps"&gt;OOP&lt;/span&gt; sometimes. Should you pick a &lt;a href="http://aspectprogramming.com/papers/PolyglotPolyParadigm_v1.pdf"&gt;poly-paradigm&lt;/a&gt; language, like Scala? Or, should you combine several languages, each of which implements one paradigm?&lt;/p&gt;


	&lt;p&gt;A potential downside of Scala is that supporting different &lt;em&gt;modularity paradigms&lt;/em&gt;, like &lt;span class="caps"&gt;OOP&lt;/span&gt; and FP, increases the complexity in the language. I think Odersky and company have done a superb job combining FP and &lt;span class="caps"&gt;OOP&lt;/span&gt; in Scala, but if you compare Scala FP code to Haskell or Erlang FP code, the latter tend to be more succinct and often easier to understand (once you learn the syntax).&lt;/p&gt;


	&lt;p&gt;Indeed, Scala will not be easy for developers to master. It will be a powerful tool for professionals. As a consultant, I work with developers with a range of skills. I would not expect some of them to prosper with Scala. Should that rule out the language? &lt;b&gt;NO&lt;/b&gt;. Rather it would be better to &amp;#8220;liberate&amp;#8221; the better developers with a more powerful tool.&lt;/p&gt;


	&lt;p&gt;So, if your application needs &lt;span class="caps"&gt;OOP&lt;/span&gt; and FP concepts interspersed, consider Scala. If your application needs discrete services, some of which are predominantly &lt;span class="caps"&gt;OOP&lt;/span&gt; and others of which are predominantly FP, then consider Scala or Java for the &lt;span class="caps"&gt;OOP&lt;/span&gt; parts and Erlang or another FP language for the FP parts.&lt;/p&gt;


	&lt;p&gt;Also, Erlang&amp;#8217;s Actor model is more mature than Scala&amp;#8217;s, so Erlang might have an edge for a highly-concurrent server application.&lt;/p&gt;


	&lt;p&gt;Of course, you should do your own analysis&amp;#8230;&lt;/p&gt;


	&lt;h3&gt;Final Thoughts&lt;/h3&gt;


	&lt;p&gt;Java the language has had a great ride. It was a godsend to us beleaguered C++ programmers in the mid &amp;#8216;90&amp;#8217;s. However, compared to Scala, Java now feels obsolete. The &lt;span class="caps"&gt;JVM&lt;/span&gt; is another story. It is arguably the best VM available.&lt;/p&gt;


	&lt;p&gt;I hope Scala replaces Java as the main &lt;span class="caps"&gt;JVM&lt;/span&gt; language for projects that prefer statically-typed languages. Fans of dynamically-typed languages might prefer JRuby, Groovy, or Jython. It&amp;#8217;s hard to argue with all the &lt;span class="caps"&gt;OOP&lt;/span&gt; and FP goodness that Scala provides. You will learn a lot about good language and application design by learning Scala. It will certainly be a prominent tool in my toolkit from now on.&lt;/p&gt;</description>
      <pubDate>Thu, 14 Aug 2008 16:00:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:d9c6812f-bb73-4568-bb96-17c9470ec0a6</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/08/14/the-seductions-of-scala-part-iii-concurrent-programming</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>Scala</category>
      <category>Java</category>
      <category>Ruby</category>
      <category>static</category>
      <category>dynamic</category>
      <category>FP</category>
      <category>OOP</category>
    </item>
    <item>
      <title>The Seductions of Scala, Part II - Functional Programming</title>
      <description>&lt;p&gt;&lt;em&gt;A Functional Programming Language for the &lt;span class="caps"&gt;JVM&lt;/span&gt;&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;In my &lt;a href="http://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i"&gt;last blog post&lt;/a&gt;, I discussed Scala&amp;#8217;s support for &lt;span class="caps"&gt;OOP&lt;/span&gt; and general improvements compared to Java. In this post, which I&amp;#8217;m posting from &lt;a href="http://www.agile2008.org/"&gt;Agile 2008&lt;/a&gt;, I discuss Scala&amp;#8217;s support for &lt;a href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional programming&lt;/a&gt; (FP) and why it should be of interest to OO developers.&lt;/p&gt;


	&lt;h3&gt;A Brief Overview of Functional Programming&lt;/h3&gt;


	&lt;p&gt;You might ask, don&amp;#8217;t most programming languages have functions? FP uses the term in the mathematical sense of the word. I hate to bring up bad memories, but you might recall from your school days that when you solved a function like&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
y = sin(x)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;for &lt;code&gt;y&lt;/code&gt;, given a value of &lt;code&gt;x&lt;/code&gt;, you could input the same value of &lt;code&gt;x&lt;/code&gt; an arbitrary number of times and you would get the same value of &lt;code&gt;y&lt;/code&gt;. This means that &lt;code&gt;sin(x)&lt;/code&gt; has no &lt;em&gt;side effects&lt;/em&gt;. In other words, unlike our &lt;em&gt;imperative&lt;/em&gt; OO or &lt;em&gt;procedural&lt;/em&gt; code, no global or object state gets changed. All the work that a mathematical function does has to be returned in the result.&lt;/p&gt;


	&lt;p&gt;Similarly, the idea of a &lt;em&gt;variable&lt;/em&gt; is a little different than what we&amp;#8217;re used to in &lt;em&gt;imperative&lt;/em&gt; code. While the value of &lt;code&gt;y&lt;/code&gt; will vary with the value of &lt;code&gt;x&lt;/code&gt;, once you have fixed &lt;code&gt;x&lt;/code&gt;, you have also fixed &lt;code&gt;y&lt;/code&gt;. The implication for FP is that &amp;#8220;variables&amp;#8221; are immutable; once assigned, they cannot be changed. I&amp;#8217;ll call such immutable variables &lt;em&gt;value objects&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Now, it would actually be hard for a &amp;#8220;pure&amp;#8221; FP language to have no side effects, ever. I/O would be rather difficult, for example, since the state of the input or output stream changes with each operation. So, in practice, all &amp;#8220;pure&amp;#8221; FP languages provide some mechanisms for breaking the rules in a controlled way.&lt;/p&gt;


	&lt;p&gt;Functions are first-class objects in FP. You can create named or anonymous functions (&lt;em&gt;e.g.&lt;/em&gt;, &lt;em&gt;closures&lt;/em&gt; or &lt;em&gt;blocks&lt;/em&gt;), assign them to variables, pass them as arguments to other functions, &lt;em&gt;etc.&lt;/em&gt; Java doesn&amp;#8217;t support this. You have to create objects that wrap the methods you want to invoke.&lt;/p&gt;


	&lt;p&gt;Functional programs tend to be much more declarative in nature than imperative programs. This is perhaps more obvious in pure FP languages, like Erlang and Haskell, than it is in Scala.&lt;/p&gt;


	&lt;p&gt;For example, the definition of Fibonacci numbers is the following.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
F(n) = F(n-1) + F(n-2) where F(1)=1 and F(2)=1
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;An here is a complete implementation in Haskell.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
module Main where 
-- Function f returns the n'th Fibonacci number. 
-- It uses binary recursion. 
f n | n &amp;lt;= 2 = 1 
    | n &amp;gt;  2 = f (n-1) + f (n-2) 
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Without understanding the intricacies of Haskell syntax, you can see that the code closely matches the &amp;#8220;specification&amp;#8221; above it. The &lt;code&gt;f n | ...&lt;/code&gt; syntax defines the function &lt;code&gt;f&lt;/code&gt; taking an argument &lt;code&gt;n&lt;/code&gt; and the two cases of &lt;code&gt;n&lt;/code&gt; values are shown on separate lines, where one case is for &lt;code&gt;n &amp;lt;= 2&lt;/code&gt; and the other case if for &lt;code&gt;n &amp;gt; 2&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;The code uses the recursive relationship between different values of the function and the special-case values when &lt;code&gt;n = 1&lt;/code&gt; and &lt;code&gt;n = 2&lt;/code&gt;. The Haskell runtime does the rest of the work.&lt;/p&gt;


	&lt;p&gt;It&amp;#8217;s interesting that most &lt;a href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html"&gt;domain-specific languages&lt;/a&gt; are also declarative in nature. Think of how JMock, EasyMock or Rails&amp;#8217; ActiveRecord code look. The code is more succinct and it lets the &amp;#8220;system&amp;#8221; do most of the heavy lifting.&lt;/p&gt;


	&lt;h3&gt;Functional Programming&amp;#8217;s Benefits for You&lt;/h3&gt;


	&lt;h4&gt;Value Objects and Side-Effect Free Functions&lt;/h4&gt;


	&lt;p&gt;It&amp;#8217;s the immutable variables and side-effect free functions that help solve the &lt;a href="http://www.technologyreview.com/Infotech/17682/page1/"&gt;multicore problem&lt;/a&gt;. Synchronized access to shared state is not required if there is no state to manage. This makes robust concurrent programs far easier to write.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;ll discuss concurrency in Scala in my third post. For now, let&amp;#8217;s discuss other ways that FP in Scala helps to improve code, concurrent or not.&lt;/p&gt;


	&lt;p&gt;Value objects are beneficial because you can pass one around without worrying that someone will change it in a way that breaks other users of the object. Value objects aren&amp;#8217;t unique to FP, of course. They have been promoted in &lt;a href="http://domaindrivendesign.org/"&gt;Domain Driven Design&lt;/a&gt; (DDD), for example.&lt;/p&gt;


	&lt;p&gt;Similarly, side-effect free functions are safer to use. There is less risk that a caller will change some state inappropriately. The caller doesn&amp;#8217;t have to worry as much about calling a function. There are fewer surprises and everything of &amp;#8220;consequence&amp;#8221; that the function does is returned to the caller. It&amp;#8217;s easier to keep to the &lt;a href="http://www.objectmentor.com/resources/articles/srp.pdf"&gt;Single Responsibility Principle&lt;/a&gt; when writing side-effect free functions.&lt;/p&gt;


	&lt;p&gt;Of course, you can write side-effect free methods and immutable variables in Java code, but it&amp;#8217;s mostly a matter of discipline; the language doesn&amp;#8217;t give you any enforcement mechanisms.&lt;/p&gt;


	&lt;p&gt;Scala gives you a helpful enforcement mechanism; the ability to declare variables as &lt;code&gt;val&lt;/code&gt;&amp;#8217;s (&lt;em&gt;i.e.,&lt;/em&gt; &amp;#8220;values&amp;#8221;) &lt;em&gt;vs.&lt;/em&gt; &lt;code&gt;var&lt;/code&gt;&amp;#8217;s (&lt;em&gt;i.e.,&lt;/em&gt; &amp;#8220;variables&amp;#8221;, um&amp;#8230; back to the imperative programming sense of the word&amp;#8230;). In fact, &lt;code&gt;val&lt;/code&gt; is the default, where neither is required by the language. Also, the Scala library contains both immutable and mutable collections and it &amp;#8220;encourages&amp;#8221; you to use the immutable collections.&lt;/p&gt;


	&lt;p&gt;However, because Scala combines both &lt;span class="caps"&gt;OOP&lt;/span&gt; and FP, it doesn&amp;#8217;t force FP purity. The upside is that you get to use the approach that best fits the problem you&amp;#8217;re trying to solve. It&amp;#8217;s interesting that some of the Scala library classes expose FP-style interfaces, immutability and side-effect free functions, while using more traditional imperative code to implement them!&lt;/p&gt;


	&lt;h4&gt;Closures and First-Class Functions&lt;/h4&gt;


	&lt;p&gt;True to its functional side, Scala gives you true closures and first-class functions. If you&amp;#8217;re a Groovy or Ruby programmer, you&amp;#8217;re used to the following kind of code.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class ExpensiveResource {
    def open(worker: () =&amp;gt; Unit) = {
        try {
            println("Doing expensive initialization")
            worker()
        } finally {
            close()
        }
    }
    def close() = {
        println("Doing expensive cleanup")
    }
}
// Example use:
try {
    (new ExpensiveResource()) open { () =&amp;gt;        // 1
        println("Using Resource")                 // 2
        throw new Exception("Thrown exception")   // 3
    }                                             // 4
} catch {
    case ex: Throwable =&amp;gt; println("Exception caught: "+ex)
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Running this code will yield:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
Doing expensive initialization
Using Resource
Doing expensive cleanup
Exception caught: java.lang.Exception: Thrown exception
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;ExpensiveResource.open&lt;/code&gt; method invokes the user-specified &lt;code&gt;worker&lt;/code&gt; function. The syntax &lt;code&gt;worker: () =&amp;gt; Unit&lt;/code&gt; defines the &lt;code&gt;worker&lt;/code&gt; parameter as a function that takes no arguments and returns nothing (recall that &lt;code&gt;Unit&lt;/code&gt; is the equivalent of &lt;code&gt;void&lt;/code&gt;).&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;ExpensiveResource.open&lt;/code&gt; handles the details of initializing the resource, invoking the worker, and doing the necessary cleanup.&lt;/p&gt;


	&lt;p&gt;The example marked with the comment &lt;code&gt;// 1&lt;/code&gt; creates a new &lt;code&gt;ExpensiveResource&lt;/code&gt;, then calls &lt;code&gt;open&lt;/code&gt;, passing it an anonymous function, called a &lt;em&gt;function literal&lt;/em&gt; in Scala terminology. The function literal is of the form &lt;code&gt;(arg_list_) =&amp;gt; function body&lt;/code&gt; or &lt;code&gt;() =&amp;gt; println(...) ...&lt;/code&gt;, in our case.&lt;/p&gt;


	&lt;p&gt;A special syntax trick is used on this line; if a method takes one argument, you can change expressions of the form &lt;code&gt;object.method(arg)&lt;/code&gt; to &lt;code&gt;object method {arg}&lt;/code&gt;. This syntax is supported to allow user-defined methods to read like control structures (think &lt;code&gt;for&lt;/code&gt; statements &amp;#8211; see the next section). If you&amp;#8217;re familiar with Ruby, the four commented lines read a lot like Ruby syntax for passing blocks to methods.&lt;/p&gt;


	&lt;p&gt;Idioms like this are very important. A library writer can encapsulate all complex, error-prone logic and allow the user to specify only the unique work required in a given situation. For example, How many times have you written code that opened an I/O stream or a database connection, used it, then cleaned up. How many times did you get the idiom &lt;a href="http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block"&gt;wrong&lt;/a&gt;, especially the proper cleanup when an exception is thrown? First-class functions allow writers of I/O, database and other resource libraries to do the correct implementation &lt;em&gt;once&lt;/em&gt;, eliminating user error and duplication. Here&amp;#8217;s a rhetorical question I always ask myself:&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;How can I make it &lt;strong&gt;impossible&lt;/strong&gt; for the user of this &lt;span class="caps"&gt;API&lt;/span&gt; to fail?&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;h4&gt;Iterations&lt;/h4&gt;


	&lt;p&gt;Iteration through collections, &lt;code&gt;Lists&lt;/code&gt; in particular, is even more common in FP than in imperative languages. Hence, iteration is highly evolved. Consider this example:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
object RequireWordsStartingWithPrefix {
    def main(args: Array[String]) = {
        val prefix = args(0)
        for {
            i &amp;lt;- 1 to (args.length - 1)   // no semicolon
            if args(i).startsWith(prefix)
        } println("args("+i+"): "+args(i))
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Compiling this code with &lt;code&gt;scalac&lt;/code&gt; and then running it on the command line with the command&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
scala RequireWordsStartingWithPrefix xx xy1 xx1 yy1 xx2 xy2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;produces the result&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
args(2): xx1
args(5): xx2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The for loop assigns a loop variable &lt;code&gt;i&lt;/code&gt; with each argument, but only if the &lt;code&gt;if&lt;/code&gt; statement is true. Instead of curly braces, the for loop argument list could also be parenthesized, but then each line as shown would have to be separated by a semi-colon, like we&amp;#8217;re used to seeing with Java for loops.&lt;/p&gt;


	&lt;p&gt;We can have an arbitrary number of assignments and conditionals. In fact, it&amp;#8217;s quite common to filter lists:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
object RequireWordsStartingWithPrefix2 {
    def main(args: Array[String]) = {
        val prefix = args(0)
        args.slice(1, args.length)
            .filter((arg: String) =&amp;gt; arg.startsWith(prefix))
            .foreach((arg: String) =&amp;gt; println("arg: "+arg))
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;This version yields the same result. In this case, the args array is sliced (loping off the search prefix), the resulting array is filtered using a function literal and the filtered array is iterated over to print out the matching arguments, again using a function literal.  This version of the algorithm should look familiar to Ruby programmers.&lt;/p&gt;


	&lt;h4&gt;Rolling Your Own &lt;em&gt;Function Objects&lt;/em&gt;&lt;/h4&gt;


	&lt;p&gt;Scala still has to support the constraints of the &lt;span class="caps"&gt;JVM&lt;/span&gt;. As a comment to the first blog post said, the Scala compiler wraps closures and &amp;#8220;bare&amp;#8221; functions in &lt;code&gt;Function&lt;/code&gt; objects. You can also make other objects behave like functions. If your object implements the &lt;code&gt;apply&lt;/code&gt; method, that method will be invoked if you put parentheses with an matching argument list on the object, as in the following example.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class HelloFunction {
    def apply() = "hello" 
    def apply(name: String) = "hello "+name
}
val hello = new HelloFunction
println(hello())        // =&amp;gt; "hello" 
println(hello("Dean"))  // =&amp;gt; "hello Dean" 
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;h4&gt;Option, None, Some&amp;#8230;&lt;/h4&gt;


	&lt;p&gt;Null pointer exceptions suck. You can still get them in Scala code, because Scala runs on the &lt;span class="caps"&gt;JVM&lt;/span&gt; and interoperates with Java libraries, but Scala offers a better way.&lt;/p&gt;


	&lt;p&gt;Typically, a reference might be null when there is nothing appropriate to assign to it. Following the conventions in some FP languages, Scala has an &lt;code&gt;Option&lt;/code&gt; type with two subtypes, &lt;code&gt;Some&lt;/code&gt;, which wraps a value, and &lt;code&gt;None&lt;/code&gt;, which is used instead of &lt;code&gt;null&lt;/code&gt;. The following example, which also demonstrates Scala&amp;#8217;s &lt;code&gt;Map&lt;/code&gt; support, shows these types in action.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
val hotLangs = Map(
    "Scala" -&amp;gt; "Rocks", 
    "Haskell" -&amp;gt; "Ethereal", 
    "Java" -&amp;gt; null)
println(hotLangs.get("Scala"))          // =&amp;gt; Some(Rocks)
println(hotLangs.get("Java"))           // =&amp;gt; Some(null)
println(hotLangs.get("C++"))            // =&amp;gt; None
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note that &lt;code&gt;Map&lt;/code&gt; stores values in &lt;code&gt;Options&lt;/code&gt; objects, as shown by the &lt;code&gt;println&lt;/code&gt; statements.&lt;/p&gt;


	&lt;p&gt;By the way, those &lt;code&gt;-&amp;gt;&lt;/code&gt; aren&amp;#8217;t special operators; they&amp;#8217;re methods. Like &lt;code&gt;::&lt;/code&gt;, valid method names aren&amp;#8217;t limited to alphanumerics, &lt;code&gt;_&lt;/code&gt;, and &lt;code&gt;$&lt;/code&gt;.&lt;/p&gt;


	&lt;h4&gt;Pattern Matching&lt;/h4&gt;


	&lt;p&gt;The last FP feature I&amp;#8217;ll discuss in this post is pattern matching, which is exploited more fully in FP languages than in imperative languages.&lt;/p&gt;


	&lt;p&gt;Using our previous definition of &lt;code&gt;hotLangs&lt;/code&gt;, here&amp;#8217;s how you might use matching.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def show(key: String) = {
    val value: Option[String] = hotLangs.get(key)
    value match {
        case Some(x) =&amp;gt; x
        case None =&amp;gt; "No hotness found" 
    }
}
println(show("Scala"))  // =&amp;gt; "Rocks" 
println(show("Java"))   // =&amp;gt; "null" 
println(show("C++"))    // =&amp;gt; "No hotness found" 
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The first &lt;code&gt;case&lt;/code&gt; statement, &lt;code&gt;case Some(x) =&amp;gt; x&lt;/code&gt;, says &amp;#8220;if the &lt;code&gt;value&lt;/code&gt; I&amp;#8217;m matching against is a &lt;code&gt;Some&lt;/code&gt; that could be constructed with the &lt;code&gt;Some[+String](x: A)&lt;/code&gt; constructor, then return the &lt;code&gt;x&lt;/code&gt;, the thing the &lt;code&gt;Some&lt;/code&gt; contains.&amp;#8221; Okay, there&amp;#8217;s a lot going on here, so more background information is in order.&lt;/p&gt;


	&lt;p&gt;In Scala, like Ruby and other languages, the last value computed in a function is returned by it. Also, almost everything returns a value, including &lt;code&gt;match&lt;/code&gt; statements, so when the &lt;code&gt;Some(x) =&amp;gt; x&lt;/code&gt; case is chosen, &lt;code&gt;x&lt;/code&gt; is returned by the &lt;code&gt;match&lt;/code&gt; and hence by the function.&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;Some&lt;/code&gt; is a generic class and the &lt;code&gt;show&lt;/code&gt; function returns a &lt;code&gt;String&lt;/code&gt;, so the match is to &lt;code&gt;Some[+String]&lt;/code&gt;. The &lt;code&gt;+&lt;/code&gt; in the &lt;code&gt;+String&lt;/code&gt; expression is analogous to Java&amp;#8217;s &lt;code&gt;extends&lt;/code&gt;, &lt;em&gt;i.e.,&lt;/em&gt; &lt;code&gt;&amp;lt;? extends String&amp;gt;&lt;/code&gt;. Capiche?&lt;/p&gt;


	&lt;p&gt;Idioms like &lt;code&gt;case Some(x) =&amp;gt; x&lt;/code&gt; are called &lt;em&gt;extractors&lt;/em&gt; in Scala and are used a lot in Scala, as well as in FP, in general. Here&amp;#8217;s another example using Lists and our friend &lt;code&gt;::&lt;/code&gt;, the &amp;#8220;cons&amp;#8221; operator.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def countScalas(list: List[String]): Int = {
    list match {
        case "Scala" :: tail =&amp;gt; countScalas(tail) + 1
        case _ :: tail       =&amp;gt; countScalas(tail)
        case Nil             =&amp;gt; 0
    }
}
val langs = List("Scala", "Java", "C++", "Scala", "Python", "Ruby")
val count = countScalas(langs)
println(count)    // =&amp;gt; 2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;We&amp;#8217;re counting the number of occurrences of &amp;#8220;Scala&amp;#8221; in a list of strings, using matching and recursion and no explicit iteration.  An expression of the form &lt;code&gt;head :: tail&lt;/code&gt; applied to a list returns the first element set as the &lt;code&gt;head&lt;/code&gt; variable and the rest of the list set as the &lt;code&gt;tail&lt;/code&gt; variable. In our case, the first &lt;code&gt;case&lt;/code&gt; statement looks for the particular case where the head equals &lt;code&gt;Scala&lt;/code&gt;. The second &lt;code&gt;case&lt;/code&gt; matches all lists, except for the empty list (&lt;code&gt;Nil&lt;/code&gt;). Since matches are eager, the first &lt;code&gt;case&lt;/code&gt; will always pick out the &lt;code&gt;List("Scala", ...)&lt;/code&gt; case first. Note that in the second &lt;code&gt;case&lt;/code&gt;, we don&amp;#8217;t actually care about the value, so we use the placeholder &lt;code&gt;_&lt;/code&gt;. Both the first and second &lt;code&gt;case&lt;/code&gt;&amp;#8217;s call &lt;code&gt;countScalas&lt;/code&gt; recursively.&lt;/p&gt;


	&lt;p&gt;Pattern matching like this is powerful, yet succinct and elegant. We&amp;#8217;ll see more examples of matching in the next blog post on concurrency using message passing.&lt;/p&gt;


	&lt;h2&gt;Recap of Scala&amp;#8217;s Functional Programming&lt;/h2&gt;


	&lt;p&gt;I&amp;#8217;ve just touched the tip of the iceberg concerning functional programming (and I hope I got all the details right!). Hopefully, you can begin to see why we&amp;#8217;ve overlooked FP for too long!&lt;/p&gt;


	&lt;p&gt;In my last post, I&amp;#8217;ll wrap up with a look at Scala&amp;#8217;s approach to concurrency, the Actor model of message passing.&lt;/p&gt;</description>
      <pubDate>Tue, 05 Aug 2008 20:32:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:e80aea1f-2ab7-41fa-b431-8d7a5a29c6ed</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/08/05/the-seductions-of-scala-part-ii-functional-programming</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>functional</category>
      <category>objects</category>
      <category>FP</category>
      <category>OOP</category>
      <category>Scala</category>
      <category>Java</category>
    </item>
    <item>
      <title>The Seductions of Scala, Part I</title>
      <description>&lt;p&gt;(Update 12/23/2008: Thanks to Apostolos Syropoulos for pointing out an earlier reference for the concept of &amp;#8220;traits&amp;#8221;).&lt;/p&gt;


	&lt;p&gt;Because of all the recent hoo-ha about &lt;a href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional programming&lt;/a&gt; (&lt;em&gt;e.g.,&lt;/em&gt; as a &amp;#8220;cure&amp;#8221; for the &lt;a href="http://www.technologyreview.com/Infotech/17682/page1/"&gt;multicore problem&lt;/a&gt;), I decided to cast aside my dysfunctional ways and learn one of the FP languages. The question was, which one?&lt;/p&gt;


	&lt;p&gt;My distinguished colleague, &lt;a href="http://www.objectmentor.com/omTeam/feathers_m.html"&gt;Michael Feathers&lt;/a&gt;, has been on a &lt;a href="http://www.haskell.org/"&gt;Haskell&lt;/a&gt; &lt;a href="http://twitter.com/mfeathers"&gt;binge&lt;/a&gt; of late. Haskell is a pure functional language and is probably most interesting as the &amp;#8220;flagship language&amp;#8221; for academic exploration, rather than production use. (That was not meant as flame bait&amp;#8230;) It&amp;#8217;s hard to underestimate the influence Haskell has had on language design, including Java generics, .NET &lt;span class="caps"&gt;LINQ&lt;/span&gt; and F#, &lt;em&gt;etc.&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;However, I decided to learn &lt;a href="http://www.scala-lang.org"&gt;Scala&lt;/a&gt; first, because it is a &lt;span class="caps"&gt;JVM&lt;/span&gt; language that combines object-oriented and functional programming in one language. At ~13 years of age, Java is a bit dated. Scala has the potential of &lt;a href="http://www.adam-bien.com/roller/abien/entry/java_net_javaone_which_programming"&gt;replacing Java&lt;/a&gt; as the principle language of the &lt;span class="caps"&gt;JVM&lt;/span&gt;, an extraordinary piece of engineering that is arguably now more valuable than the language itself. (Note: there is also a .NET version of Scala under development.)&lt;/p&gt;


	&lt;p&gt;Here are some of my observations, divided over three blog posts.&lt;/p&gt;


	&lt;p&gt;First, a few disclaimers. I am a Scala novice, so any flaws in my analysis reflect on me, not Scala! Also, this is by no means an exhaustive analysis of the pros and cons of Scala &lt;em&gt;vs.&lt;/em&gt; other options. Start with the &lt;a href="http://www.scala-lang.org"&gt;Scala website&lt;/a&gt; for more complete information.&lt;/p&gt;


	&lt;h2&gt;A Better &lt;span class="caps"&gt;OOP&lt;/span&gt; Language&lt;/h2&gt;


	&lt;p&gt;Scala works seamlessly with Java. You can invoke Java APIs, extend Java classes and implement Java interfaces. You can even invoke Scala code from Java, once you understand how certain &amp;#8220;Scala-isms&amp;#8221; are translated to Java constructs (&lt;code&gt;javap&lt;/code&gt; is your friend). Scala syntax is more succinct and removes a lot of tedious boilerplate from Java code.&lt;/p&gt;


	&lt;p&gt;For example, the following &lt;code&gt;Person&lt;/code&gt; class in Java:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class Person {
    private String firstName;
    private String lastName;
    private int    age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName  = lastName;
        this.age       = age;
    }

    public void setFirstName(String firstName) { this.firstName = firstName; }
    public void String getFirstName() { return this.firstName; }
    public void setLastName(String lastName) { this.lastName = lastName; }
    public void String getLastName() { return this.lastName; }
    public void setAge(int age) { this.age = age; }
    public void int getAge() { return this.age; }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;can be written in Scala thusly:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class Person(var firstName: String, var lastName: String, var age: Int)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Yes, that&amp;#8217;s it. The constructor is the argument list to the class, where each parameter is declared as a variable (&lt;code&gt;var&lt;/code&gt; keyword). It automatically generates the &lt;em&gt;equivalent&lt;/em&gt; of getter and setter methods, meaning they look like Ruby-style attribute accessors; the getter is &lt;code&gt;foo&lt;/code&gt; instead of &lt;code&gt;getFoo&lt;/code&gt; and the setter is &lt;code&gt;foo = &lt;/code&gt; instead of &lt;code&gt;setFoo&lt;/code&gt;. Actually, the setter function is really &lt;code&gt;foo_=&lt;/code&gt;, but Scala lets you use the &lt;code&gt;foo = &lt;/code&gt; &lt;em&gt;sugar&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Lots of other well designed conventions allow the language to define almost everything as a method, yet support forms of syntactic sugar like the illusion of operator overloading, Ruby-like &lt;span class="caps"&gt;DSL&lt;/span&gt;&amp;#8217;s, &lt;em&gt;etc.&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;You also get fewer semicolons, no requirements tying package and class definitions to the file system structure, type inference, multi-valued returns (tuples), and a better type and generics model.&lt;/p&gt;


	&lt;p&gt;One of the biggest deficiencies of Java is the lack of a complete &lt;em&gt;mixin&lt;/em&gt; model. Mixins are small, focused (think &lt;a href="http://www.objectmentor.com/resources/articles/srp.pdf"&gt;Single Responsibility Principle&lt;/a&gt; ...) bits of state and behavior that can be added to classes (or objects) to extend them as needed. In a language like C++, you can use multiple inheritance for mixins. Because Java only supports single inheritance and interfaces, which can&amp;#8217;t have any state and behavior, implementing a mixin-based design has always required various hacks. &lt;a href="http://www.aosd.net"&gt;Aspect-Oriented Programming&lt;/a&gt; is also one &lt;em&gt;partial&lt;/em&gt; solution to this problem.&lt;/p&gt;


	&lt;p&gt;The most exciting &lt;span class="caps"&gt;OOP&lt;/span&gt; enhancement Scala brings is its support for  &lt;a href="http://www.scala-lang.org/intro/traits.html"&gt;Traits&lt;/a&gt;, a concept first described &lt;a href="http://portal.acm.org/citation.cfm?doid=800210.806468"&gt;here&lt;/a&gt; and more recently discussed &lt;a href="http://portal.acm.org/citation.cfm?id=1119479.1119483"&gt;here&lt;/a&gt;. Traits support Mixins (and other design techniques) through composition rather than inheritance. You could think of traits as interfaces with implementations. They work a lot like Ruby modules.&lt;/p&gt;


	&lt;p&gt;Here is an example of the &lt;a href="http://en.wikipedia.org/wiki/Observer_pattern"&gt;Observer Pattern&lt;/a&gt; written as traits, where they are used to monitor changes to a bank account balance. First, here are reusable &lt;code&gt;Subject&lt;/code&gt; and &lt;code&gt;Observer&lt;/code&gt; traits.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
trait Observer[S] {
    def receiveUpdate(subject: S);
}

trait Subject[S] { 
    this: S =&amp;gt;
    private var observers: List[Observer[S]] = Nil
    def addObserver(observer: Observer[S]) = observers = observer :: observers

    def notifyObservers() = observers.foreach(_.receiveUpdate(this))
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;In Scala, generics are declared with square brackets, &lt;code&gt;[...]&lt;/code&gt;, rather than angled brackets, &lt;code&gt;&amp;lt;...&amp;gt;&lt;/code&gt;. Method definitions begin with the &lt;code&gt;def&lt;/code&gt; keyword. The &lt;code&gt;Observer&lt;/code&gt; trait defines one abstract method, which is called by the &lt;code&gt;Subject&lt;/code&gt; to notify the observer of changes. The &lt;code&gt;Subject&lt;/code&gt; is passed to the &lt;code&gt;Observer&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;This trait looks exactly like a Java interface. In fact, that&amp;#8217;s how traits are represented in Java byte code. If the trait has state and behavior, like &lt;code&gt;Subject&lt;/code&gt;, the byte code representation involves additional elements.&lt;/p&gt;


	&lt;p&gt;The &lt;code&gt;Subject&lt;/code&gt; trait is more complex. The strange line, &lt;code&gt;this: S =&amp;gt; &lt;/code&gt;, is called a &lt;em&gt;self type&lt;/em&gt; declaration. It tells the compiler that whenever &lt;code&gt;this&lt;/code&gt; is referenced in the trait, treat its type as &lt;code&gt;S&lt;/code&gt;, rather than &lt;code&gt;Subject[S]&lt;/code&gt;. Without this declaration, the call to &lt;code&gt;receiveUpdate&lt;/code&gt; in the &lt;code&gt;notifyObservers&lt;/code&gt; method would not compile, because it would attempt to pass a &lt;code&gt;Subject[S]&lt;/code&gt; object, rather than a &lt;code&gt;S&lt;/code&gt; object. The self type declaration solves this problem.&lt;/p&gt;


	&lt;p&gt;The next line creates a private list of observers, initialized to &lt;code&gt;Nil&lt;/code&gt;, which is an empty list. Variable declarations are &lt;code&gt;name: type&lt;/code&gt;. Why didn&amp;#8217;t they follow Java conventions, &lt;em&gt;i.e.,&lt;/em&gt; &lt;code&gt;type name&lt;/code&gt;? Because this syntax makes the code easier to parse when &lt;em&gt;type inference&lt;/em&gt; is used, meaning where the explicit &lt;code&gt;:type&lt;/code&gt; is omitted and inferred.&lt;/p&gt;


	&lt;p&gt;In fact, I&amp;#8217;m using type inference for all the method declarations, because the compiler can figure out what each method returns, in my examples. In this case, they all return type &lt;code&gt;Unit&lt;/code&gt;, the equivalent of Java&amp;#8217;s &lt;code&gt;void&lt;/code&gt;. (The name &lt;code&gt;Unit&lt;/code&gt; is a common term in functional languages.)&lt;/p&gt;


	&lt;p&gt;The third line defines a method for adding a new observer to the list. Notice that concrete method definitions are of the form&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def methodName(parameter: type, ...) = {
    method body
}  
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;In this case, because there is only one line, I dispensed with the &lt;code&gt;{...}&lt;/code&gt;. The equals sign before the body emphasizes the functional nature of scala, that all methods are objects, too. We&amp;#8217;ll revisit this in a moment and in the next post.&lt;/p&gt;


	&lt;p&gt;The method body prepends the new observer object to the existing list. Actually, a new list is created. The &lt;code&gt;::&lt;/code&gt; operator, called &amp;#8220;cons&amp;#8221;, &lt;em&gt;binds to the right&lt;/em&gt;. This &amp;#8220;operator&amp;#8221; is really a method call, which could actually be written like this, &lt;code&gt;observers.::(observer)&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;Our final method in &lt;code&gt;Subject&lt;/code&gt; is &lt;code&gt;notifyObservers&lt;/code&gt;. It iterates through observers and invokes the block &lt;code&gt;observer.receiveUpdate(this)&lt;/code&gt; on each observer. The &lt;code&gt;_&lt;/code&gt; evaluates to the current observer reference. For comparison, in Ruby, you would define this method like so:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def notifyObservers() 
    @observers.each { |o| o.receiveUpdate(self) }
end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Okay, let&amp;#8217;s look at how you would actually use these traits. First, our &amp;#8220;plain-old Scala object&amp;#8221; (POSO) &lt;code&gt;Account&lt;/code&gt;.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class Account(initialBalance: Double) {
    private var currentBalance = initialBalance
    def balance = currentBalance
    def deposit(amount: Double)  = currentBalance += amount
    def withdraw(amount: Double) = currentBalance -= amount
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Hopefully, this is self explanatory, except for two things. First, recall that the whole class declaration is actually the constructor, which is why we have an &lt;code&gt;initialBalance: Double&lt;/code&gt; parameter on &lt;code&gt;Account&lt;/code&gt;. This looks strange to the Java-trained eye, but it actually works well and is another example of Scala&amp;#8217;s economy. (You can define multiple constructors, but I won&amp;#8217;t go into that here&amp;#8230;).&lt;/p&gt;


	&lt;p&gt;Second, note that I omitted the parentheses when I defined the &lt;code&gt;balance&lt;/code&gt; &amp;#8220;getter&amp;#8221; method. This supports the &lt;em&gt;uniform access principle&lt;/em&gt;. Clients will simply call &lt;code&gt;myAccount.balance&lt;/code&gt;, without parentheses and I could redefine &lt;code&gt;balance&lt;/code&gt; to be a &lt;code&gt;var&lt;/code&gt; or &lt;code&gt;val&lt;/code&gt; and the client code would not have to change!&lt;/p&gt;


	&lt;p&gt;Next, a subclass that supports observation.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class ObservedAccount(initialBalance: Double) extends Account(initialBalance) with Subject[Account] {
    override def deposit(amount: Double) = {
        super.deposit(amount)
        notifyObservers()
    }
    override def withdraw(amount: Double) = {
        super.withdraw(amount)
        notifyObservers()
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;with&lt;/code&gt; keyword is how a trait is used, much the way that you &lt;code&gt;implement&lt;/code&gt; an interface in Java, but now you don&amp;#8217;t have to implement the interface&amp;#8217;s methods. We&amp;#8217;ve already done that.&lt;/p&gt;


	&lt;p&gt;Note that the expression, &lt;code&gt;ObservedAccount(initialBalance: Double) extends Account(initialBalance)&lt;/code&gt;, not only defines the (single) inheritance relationship, it also functions as the constructor&amp;#8217;s call to &lt;code&gt;super(initialBalance)&lt;/code&gt;, so that &lt;code&gt;Account&lt;/code&gt; is properly initialized.&lt;/p&gt;


	&lt;p&gt;Next, we have to override the &lt;code&gt;deposit&lt;/code&gt; and &lt;code&gt;withdraw&lt;/code&gt; methods, calling the parent methods and then invoking &lt;code&gt;notifyObservers&lt;/code&gt;. Anytime you override a concrete method, scala requires the &lt;code&gt;override&lt;/code&gt; keyword. This tells you unambiguously that you are overriding a method and the Scala compiler throws an error if you aren&amp;#8217;t actually overriding a method, &lt;em&gt;e.g.,&lt;/em&gt; because of a typo. Hence, the keyword is much more reliable (and hence useful&amp;#8230;) than Java&amp;#8217;s &lt;code&gt;@Override&lt;/code&gt; annotation.&lt;/p&gt;


	&lt;p&gt;Finally, here is an &lt;code&gt;Observer&lt;/code&gt; that prints to stdout when the balance changes.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class AccountReporter extends Observer[Account] {
    def receiveUpdate(account: Account) =
        println("Observed balance change: "+account.balance)
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Rather than use &lt;code&gt;with&lt;/code&gt;, I just extend the &lt;code&gt;Observer&lt;/code&gt; trait, because I don&amp;#8217;t have another parent class.&lt;/p&gt;


	&lt;p&gt;Here&amp;#8217;s some code to test what we&amp;#8217;ve done.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def changingBalance(account: Account) = {
    println("==== Starting balance: " + account.balance)
    println("Depositing $10.0")
    account.deposit(10.0)
    println("new balance: " + account.balance)
    println("Withdrawing $5.60")
    account.withdraw(5.6)
    println("new balance: " + account.balance)
}

var a = new Account(0.0)
changingBalance(a)

var oa = new ObservedAccount(0.0)
changingBalance(oa)
oa.addObserver(new AccountReporter)
changingBalance(oa)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Which prints out:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
==== Starting balance: 0.0
Depositing $10.0
new balance: 10.0
Withdrawing $5.60
new balance: 4.4
==== Starting balance: 0.0
Depositing $10.0
new balance: 10.0
Withdrawing $5.60
new balance: 4.4
==== Starting balance: 4.4
Depositing $10.0
Observed balance change: 14.4
new balance: 14.4
Withdrawing $5.60
Observed balance change: 8.8
new balance: 8.8
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note that we only observe the last transaction.&lt;/p&gt;


	&lt;p&gt;&lt;a href="http://www.scala-lang.org/downloads/index.html"&gt;Download Scala&lt;/a&gt; and try it out. Put all this code in one &lt;code&gt;observer.scala&lt;/code&gt; file, for example, and run the command:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
scala observer.scala
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;h2&gt;But Wait, There&amp;#8217;s More!&lt;/h2&gt;


	&lt;p&gt;In the next post, I&amp;#8217;ll look at Scala&amp;#8217;s support for Functional Programming and why OO programmers should find it interesting. In the third post, I&amp;#8217;ll look at the specific case of concurrent programming in Scala and make some concluding observations of the pros and cons of Scala.&lt;/p&gt;


	&lt;p&gt;For now, here are some references for more information.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;The &lt;a href="http://www.scala-lang.org"&gt;Scala website&lt;/a&gt;, for downloads, documentation, mailing lists, &lt;em&gt;etc.&lt;/em&gt;&lt;/li&gt;
		&lt;li&gt;Ted Neward&amp;#8217;s excellent &lt;a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=scala+neward"&gt;multipart introduction&lt;/a&gt; to Scala at &lt;a href="http://www.ibm.com/developerworks"&gt;developerWorks&lt;/a&gt;.&lt;/li&gt;
		&lt;li&gt;The forthcoming &lt;a href="http://www.artima.com/shop/programming_in_scala"&gt;Programming in Scala&lt;/a&gt; book.&lt;/li&gt;
	&lt;/ul&gt;</description>
      <pubDate>Sun, 03 Aug 2008 15:30:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:d4a4acbf-e300-4146-83c7-0536785997e1</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>Java</category>
      <category>Scala</category>
      <category>statically</category>
      <category>typed</category>
      <category>dynamically</category>
      <category>OOP</category>
      <category>FP</category>
      <category>functional</category>
      <category>object</category>
      <category>oriented</category>
    </item>
  </channel>
</rss>

