<?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 Java</title>
    <link>http://blog.objectmentor.com/articles/tag/java</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <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 +0000</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 +0000</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 +0000</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;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?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 +0000</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>
    <item>
      <title>Always &amp;lt;tt&amp;gt;close()&amp;lt;/tt&amp;gt; in a &amp;lt;tt&amp;gt;finally&amp;lt;/tt&amp;gt; block</title>
      <description>&lt;p&gt;Here&amp;#8217;s one for my fellow Java programmers, but it&amp;#8217;s really generally applicable.&lt;/p&gt;


	&lt;p&gt;When you call &lt;tt&gt;close()&lt;/tt&gt; on I/O streams, readers, writers, network sockets, database connections, &lt;em&gt;etc.&lt;/em&gt;, it&amp;#8217;s easy to forgot the most appropriate idiom. I just spent a few hours fixing some examples of misuse in otherwise very good Java code.&lt;/p&gt;


	&lt;p&gt;What&amp;#8217;s wrong the following code?&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
public void writeContentToFile(String content, String fileName) throws Exception {
    File output = new File(fileName);
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(output), "UTF-8");
    writer.write(content);
    writer.close();
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;It doesn&amp;#8217;t look all that bad. It tells it&amp;#8217;s story. It&amp;#8217;s easy to understand.&lt;/p&gt;


	&lt;p&gt;However, &lt;em&gt;it&amp;#8217;s quite likely&lt;/em&gt; that you won&amp;#8217;t get to the last line, which closes the &lt;tt&gt;writer&lt;/tt&gt;, from time to time. File and network I/O errors are common. For example, what if you can&amp;#8217;t actually write to the location specified by &lt;tt&gt;fileName&lt;/tt&gt;? So, we have to be more defensive. We want to be sure we always clean up.&lt;/p&gt;


	&lt;p&gt;The correct idiom is to use a &lt;tt&gt;try &amp;#8230; finally &amp;#8230;&lt;/tt&gt; block.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
public void writeContentToFile(String content, String fileName) throws Exception {
    File output = new File(getFileSystemPath() + contentFilename);
    OutputStreamWriter writer = null;
    try {
        writer = new OutputStreamWriter(new FileOutputStream(output), "UTF-8");
        writer.write(content);
    } finally {
        if (writer != null)
            writer.close();
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Now, no matter what happens, the writer will be closed, if it&amp;#8217;s not null, even if writing the output was unsuccessful.&lt;/p&gt;


	&lt;p&gt;Note that we don&amp;#8217;t necessarily need a &lt;tt&gt;catch&lt;/tt&gt; block, because in this case we&amp;#8217;re willing to let any &lt;tt&gt;Exception&lt;/tt&gt;s propagate up the stack (notice the throws clause). A lot of developers don&amp;#8217;t realize that there are times when you need a &lt;tt&gt;try&lt;/tt&gt; block, but not necessarily a &lt;tt&gt;catch&lt;/tt&gt; block. This is one of those times.&lt;/p&gt;


	&lt;p&gt;So, anytime you need to clean up or otherwise release resources, use a &lt;tt&gt;finally&lt;/tt&gt; block to ensure that the clean up happens, no matter what.&lt;/p&gt;</description>
      <pubDate>Thu, 31 Jul 2008 00:12:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:2eda3563-e87a-4c15-a93d-f842f8de8f68</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/07/31/always-close-in-a-finally-block</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>close</category>
      <category>finally</category>
      <category>Java</category>
    </item>
    <item>
      <title>Writing Java Aspects ... with JRuby and Aquarium!</title>
      <description>&lt;p&gt;&lt;a href="http://aquarium.rubyforge.org"&gt;Aquarium&lt;/a&gt; V0.4.0, my &lt;span class="caps"&gt;AOP&lt;/span&gt; library for Ruby, now supports &lt;a href="http://jruby.codehaus.org/"&gt;JRuby&lt;/a&gt;. Not only do the regular &amp;#8220;pure Ruby&amp;#8221; Aquarium specs run reliably under JRuby (V1.1RC2), but you can now write aspects for Java types with Aquarium!&lt;/p&gt;


	&lt;p&gt;There are some &lt;strong&gt;important&lt;/strong&gt; limitations, though. Cartographers of old would mark dangerous or unknown territory on their maps with &lt;a href="http://en.wikipedia.org/wiki/Here_be_dragons"&gt;&lt;em&gt;hic sunt dracones&lt;/em&gt;&lt;/a&gt; (&amp;#8220;here be dragons&amp;#8221;), a reference to the old practice of adorning maps with serpents around the edges.&lt;/p&gt;


	&lt;p&gt;This is true of Aqurium + Java types in JRuby, too, at least for now.&lt;/p&gt;


	&lt;p&gt;Aquarium uses Ruby&amp;#8217;s metaprogramming &lt;span class="caps"&gt;API&lt;/span&gt; extensively and the JRuby team has done some pretty sophisticated work to integrate Java types with Ruby. Hence, it&amp;#8217;s not too surprising there are some &lt;em&gt;gotchas&lt;/em&gt;. Hopefully, workarounds will be possible for all of them.&lt;/p&gt;


	&lt;p&gt;The details are discussed on the &lt;a href="http://aquarium.rubyforge.org/jruby.htm"&gt;JRuby page&lt;/a&gt;, the &lt;a href="http://aquarium.rubyforge.org/rdoc/files/README.html"&gt;&lt;span class="caps"&gt;README&lt;/span&gt;&lt;/a&gt; on the Aquarium site, and of course the &amp;#8220;specs&amp;#8221; in the distribution&amp;#8217;s &lt;code&gt;jruby/spec&lt;/code&gt; directory. I&amp;#8217;ll summarize them here, after discussing the pros and cons of Aquarium &lt;em&gt;vs.&lt;/em&gt; the venerable &lt;a href="http://www.aspectj.org"&gt;AspectJ&lt;/a&gt; and showing you an example of using Aquarium for Java.&lt;/p&gt;


	&lt;p&gt;Briefly, Aquarium&amp;#8217;s advantages over AspectJ are these:&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;You can add &lt;strong&gt;and&lt;/strong&gt; remove advice dynamically at runtime. You can&amp;#8217;t remove AspectJ advice.&lt;/li&gt;
		&lt;li&gt;You can advise &lt;span class="caps"&gt;JDK&lt;/span&gt; types easily with Aquarium. AspectJ won&amp;#8217;t do this by default, but this is really more of a legacy licensing issue than a real technical limitation.&lt;/li&gt;
		&lt;li&gt;You can advise individual &lt;em&gt;objects&lt;/em&gt;, not just types.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;Aquarium&amp;#8217;s disadvantages compared to AspectJ include:&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;Aquarium will be slower than using AspectJ (although this has not been studied in depth yet).&lt;/li&gt;
		&lt;li&gt;Aquarium&amp;#8217;s pointcut language is not as full-featured as AspectJ&amp;#8217;s.&lt;/li&gt;
		&lt;li&gt;There are the bugs and limitations I mentioned above in this initial V0.4.0 release, which I&amp;#8217;ll elaborate shortly.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;Here is an example of adding tracing calls to a method &lt;code&gt;doIt&lt;/code&gt; in all classes that implement the Java interface &lt;code&gt;com.foo.Work&lt;/code&gt;.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
Aspect.new :before, :calls_to =&amp;gt; [:doIt, :do_it], :in_types_and_descendents =&amp;gt; Java::com.foo.Work do |jp, obj, *args|
  log "Entering: #{jp.target_type.name}##{jp.method_name}: object = #{object}, args = #{args.inspect}" 
end
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;There are two important points to notice in this example:&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;You can choose to refer to the method as &lt;code&gt;do_it&lt;/code&gt; (Ruby style) or &lt;code&gt;doIt&lt;/code&gt;, but these variants are effectively treated as &lt;strong&gt;separate&lt;/strong&gt; methods; advice on one will not affect invocations of the other. So, if you want to be sure to catch &lt;strong&gt;all&lt;/strong&gt; invocations, use &lt;strong&gt;both&lt;/strong&gt; forms. There is a bug (18326) that happens in certain conditions if you use just the Java naming convention.&lt;/li&gt;
		&lt;li&gt;If the type is an interface, you must use &lt;code&gt;:types_and_descendents&lt;/code&gt; (or one of the supported variants on the word &lt;code&gt;types&lt;/code&gt;...). Since interfaces don&amp;#8217;t have method implementations, you will match no join points unless you use the &lt;code&gt;_and_descendents&lt;/code&gt; clause. (By default, Aquarium warns you when no join points are matched by an aspect.) However, there is a bug (18325) with this approach if Java types are subtyped in Ruby.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;h4&gt;Limitations and Bugs&lt;/h4&gt;


	&lt;p&gt;Okay, here&amp;#8217;s the &amp;#8220;fine print&amp;#8221;...&lt;/p&gt;


	&lt;p&gt;In this (V0.4.0) release, there are some important limitations.&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;Aquarium advice on a method in a Java type will &lt;strong&gt;only&lt;/strong&gt; be invoked when the method is called &lt;strong&gt;directly&lt;/strong&gt; from Ruby.&lt;/li&gt;
		&lt;li&gt;To have the advice invoked when the method is called from &lt;strong&gt;either&lt;/strong&gt; Java &lt;strong&gt;or&lt;/strong&gt; Ruby, it is necessary to create a Ruby subclass of the Java type and override the method(s) you want to advise. These overrides can just call &lt;code&gt;super&lt;/code&gt;. Note that it will also be necessary for &lt;strong&gt;instances&lt;/strong&gt; of this Ruby type to be used throughout the application, in both the Java and Ruby code. So, you&amp;#8217;ll have to instantiate the object in your Ruby code.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;Yea, this isn&amp;#8217;t so great, but if you&amp;#8217;re motivated&amp;#8230; ;)&lt;/p&gt;


	&lt;p&gt;There are also a few outstanding Aquarium bugs (which could actually be JRuby bugs or quirks of the Aquarium-JRuby &amp;#8220;interaction&amp;#8221;; I&amp;#8217;m not yet sure which).&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;&lt;strong&gt;Bug #18325&lt;/strong&gt;: If you have Ruby subclasses of Java types &lt;strong&gt;and&lt;/strong&gt; you advise a Java method in the hierarchy using &lt;code&gt;:types_and_descendents =&amp;gt; MyJavaBaseClassOrInterface&lt;/code&gt; &lt;strong&gt;and&lt;/strong&gt; you call unadvise on the aspect, the advice &amp;#8220;infrastructure&amp;#8221; is not correctly removed from the Ruby types. Workaround: Either don&amp;#8217;t &amp;#8220;unadvise&amp;#8221; such Ruby types or only advise methods in such Ruby types where the method is explicitly overridden in the Ruby class. (The spec and the &lt;a href="http://rubyforge.org/tracker/index.php?func=detail&amp;#38;aid=18325&amp;#38;group_id=4281&amp;#38;atid=16494"&gt;Rubyforge bug report&lt;/a&gt; provide examples.)&lt;/li&gt;
		&lt;li&gt;&lt;strong&gt;Bug #18326&lt;/strong&gt;: Normally, you can use either Java- or Ruby-style method names (&lt;em&gt;e.g.,&lt;/em&gt; &lt;code&gt;doSomething&lt;/code&gt; vs. &lt;code&gt;do_something&lt;/code&gt;), for Java types. However, if you write an aspect using the Java-style for a method name and a Ruby subclass of the Java type where the method is actually defined (i.e., the Ruby class doesn&amp;#8217;t override the method), Aquarium acts like the JoinPoint is advised, but the advice is never actually called. Workaround: Use the Ruby-style name in this scenario.&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;So, there is still some work to do, but it&amp;#8217;s promising that you can use an aspect framework in one language with another. A primary goal of Aquarium is to make it easy to write simple aspects. My hope is that people who might find AspectJ daunting will still give Aquarium a try.&lt;/p&gt;</description>
      <pubDate>Mon, 25 Feb 2008 22:10:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:4645fddb-ba4f-4e8d-8283-7732439d017f</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/02/25/writing-java-aspects-with-jruby-and-aquarium</link>
      <category>JRuby</category>
      <category>aquarium</category>
      <category>Java</category>
      <category>aspects</category>
      <category>AOP</category>
      <category>AOSD</category>
    </item>
    <item>
      <title>CJUG West 9/6/07: Aspect-Oriented Programming and Software Design</title>
      <description>&lt;p&gt;I&amp;#8217;m giving a talk at the &lt;a href="http://www.cjug.org/Wiki.jsp?page=Welcome"&gt;Chicago Java User&amp;#8217;s Group West&lt;/a&gt; meeting this Thursday at 6:30 PM. The topic is &lt;a href="http://www.cjug.org/Wiki.jsp?page=2007.09.06.west"&gt;Aspect-Oriented Programming and Software Design in Java and AspectJ&lt;/a&gt;. I&amp;#8217;ll briefly describe the problems that &lt;span class="caps"&gt;AOP&lt;/span&gt; addresses and how the principles of object-oriented design influence &lt;span class="caps"&gt;AOP&lt;/span&gt; and &lt;i&gt;vice versa&lt;/i&gt;. If you&amp;#8217;re in the area, I hope to see you &lt;a href="http://www.cjug.org/Wiki.jsp?page=2007.09.06.west"&gt;there&lt;/a&gt;.&lt;/p&gt;</description>
      <pubDate>Tue, 04 Sep 2007 17:55:47 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:bd3e42fa-602d-4d02-9aef-7f5332628a19</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2007/09/04/cjug-west-9-6-07-aspect-oriented-programming-and-software-design</link>
      <category>Dean's Deprecations</category>
      <category>Public Speaking Engagements</category>
      <category>AOP</category>
      <category>AOD</category>
      <category>design</category>
      <category>Java</category>
      <category>AspectJ</category>
      <category>CJUG</category>
      <trackback:ping>http://blog.objectmentor.com/articles/trackback/8802</trackback:ping>
    </item>
    <item>
      <title>Applications Should Use Several Languages</title>
      <description>&lt;p&gt;Yesterday, I &lt;a href="http://typo.objectmentor.com/articles/2007/07/03/observations-on-tdd-in-c-long"&gt;blogged&lt;/a&gt; about &lt;a href="http://typo.objectmentor.com/articles/2007/07/03/observations-on-tdd-in-c-long"&gt;&lt;span class="caps"&gt;TDD&lt;/span&gt; in C++&lt;/a&gt; and ended with a suggestion for the dilemma of needing optimal performance some of the time and optimal productivity the rest of the time. I suggested that you should use more than one language for your applications.&lt;/p&gt;


	&lt;p&gt;If you are developing web applications, you are already doing this, of course. Your web tier probably uses several &amp;#8220;languages&amp;#8221;, &lt;em&gt;e.g.,&lt;/em&gt; HTML, JavaScript, &lt;span class="caps"&gt;JSP&lt;/span&gt;/ASP, &lt;span class="caps"&gt;CSS&lt;/span&gt;, Java, &lt;em&gt;etc.&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;However, most people use only one language for the business/mid tier. I think you should consider using several; a high-productivity language environment for most of your work, with the occasional critical functionality implemented in C or C++ to optimize performance, but &lt;em&gt;only after actually measuring&lt;/em&gt; where the bottlenecks are located.&lt;/p&gt;


	&lt;p&gt;This approach is much too rare, but it has historical precedents. One of the most successful and long-lived software projects of all time is Emacs. It consists of a core C-based runtime with most of the functionality implemented in Emacs lisp &amp;#8220;components&amp;#8221;. The relative ease of extending Emacs using lisp has resulted in a rich assortment of support tools for various operating systems, languages, build tools, &lt;em&gt;etc.&lt;/em&gt; Even modern IDEs and and other graphical editors have not completely displaced Emacs.&lt;/p&gt;


	&lt;p&gt;Java has embraced the mixed language philosophy somewhat reluctantly. &lt;span class="caps"&gt;JNI&lt;/span&gt; is the official and most commonly-used &lt;span class="caps"&gt;API&lt;/span&gt; for invoking &amp;#8220;native&amp;#8221; code, but it is somewhat hard to use and few people actually use it. In contrast, for example, the Ruby world has always embraced this approach. Ruby has an easy to use &lt;span class="caps"&gt;API&lt;/span&gt; for invoking native C code and good alternatives exist for invoking code in other languages. As a result, many of the 3rd-party Ruby libraries (or &lt;em&gt;gems&lt;/em&gt;) contain both Ruby and native C code. The latter is built on the fly when you install the gem. Hence, there are many high-performance Ruby applications. This is not a contradiction in terms, because the performance-critical sections run natively, even though interpreted Ruby is relatively slow.&lt;/p&gt;


	&lt;p&gt;Of course, you have to be judicious in how you use mixed-language programming. Crossing the language boundary is often somewhat heavyweight, so you should avoid doing such invocations inside tight loops, for example.&lt;/p&gt;


	&lt;p&gt;So, I think the solution to the dilemma of needing high performance sometimes and high productivity the rest of the time is to pick the right tools for each circumstance and make them interoperate. Even constrained embedded devices like cell phones would  be easier to implement if most of the code were written in a language like Ruby, Python, Smalltalk, or Java and performance-critical components were written in C or C++.&lt;/p&gt;


	&lt;p&gt;If I were starting such a greenfield project, I would assume that &lt;em&gt;time-to-money&lt;/em&gt; is the top priority and write most of my code in Ruby (my personal current favorite), using &lt;span class="caps"&gt;TDD&lt;/span&gt; of course. I would profile it constantly, as part of the nightly or &lt;a href="http://www.martinfowler.com/articles/continuousIntegration.html"&gt;continuous-integration&lt;/a&gt; build. When bottlenecks emerge, I would first determine if a refactoring is sufficient to fix them and if not, I would rewrite the critical sections in C. If the project were for an embedded device, I would also watch the resource usage carefully.&lt;/p&gt;


	&lt;p&gt;For my embedded device, I would test from the beginning whether or not the overhead of the interpreter/VM and the overall performance are acceptable. I would also be sure that I have adequate tool support for the inevitable remote debugging and diagnostics I&amp;#8217;ll have to do. If I made the wrong tool choices after all, I would know early on, when it&amp;#8217;s still relatively painless to retool.&lt;/p&gt;


	&lt;p&gt;If you&amp;#8217;re an IT or web-site developer, you have fewer performance limitations and more options. You might decide to make the cross-language boundary a &lt;em&gt;cross-process&lt;/em&gt; boundary, &lt;em&gt;e.g.,&lt;/em&gt; by communicating through some sort of &lt;em&gt;lightweight&lt;/em&gt; web services. This is one way to leverage legacy C/C++ code while developing new functionality in a more productive language.&lt;/p&gt;</description>
      <pubDate>Wed, 04 Jul 2007 11:38:31 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:d93783af-ac4e-43c1-a405-e86ebb1d9efa</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2007/07/04/applications-should-use-several-languages</link>
      <category>Dean's Deprecations</category>
      <category>c</category>
      <category>Ruby</category>
      <category>Java</category>
      <category>Smalltalk</category>
      <category>design</category>
      <category>architecture</category>
      <trackback:ping>http://blog.objectmentor.com/articles/trackback/8786</trackback:ping>
    </item>
    <item>
      <title>Protecting Developers from Powerful Languages</title>
      <description>&lt;p&gt;Microsoft&amp;#8217;s forthcoming C# version 3 has some innovative features, as described in this &lt;a href="http://tomasp.net/articles/csharp3-concepts.aspx"&gt;blog&lt;/a&gt;. I give the C# team credit for pushing the boundaries of C#, in part because they have forced the Java community to follow suit. ;)
&lt;/p&gt;
&lt;p&gt;A common tension in many development shops is how far to trust the developers with languages and tools that are perceived to be &amp;#8220;advanced&amp;#8221;. It&amp;#8217;s tempting to limit developers to &amp;#8220;safe&amp;#8221; languages and maybe not all the features of those languages. This can be misguided.&lt;/p&gt;

&lt;p&gt;Java is usually considered safe, but Java Generics are suspect. Strong typing is safe, but dynamic typing isn&amp;#8217;t controlled enough. Closures and continuations sound too advanced and technical to be trusted in the hands of &amp;#8220;our team&amp;#8221;.&lt;/p&gt;
&lt;p&gt;To be fair, larger organizations have more at stake and caution is prudent. Regrettably, it is also true that many people in our profession are &amp;#8230; hmm &amp;#8230; not that well qualified.&lt;/p&gt;
&lt;p&gt;However, I find that I&amp;#8217;m far more productive and less likely to make mistakes using Ruby iterators with closures than writing more verbose and inelegant  Java.&lt;/p&gt;
&lt;p&gt;I used to be a strong believer in static typing, but it has become a distraction, as I have to worry more about the types of method parameters and return values, rather than just worrying about the &lt;i&gt;values&lt;/i&gt; themselves. I realized that, on average in a typical section of code, the actual type of a variable is unimportant. The variable is just a &amp;#8220;handle&amp;#8221; being passed around. The name is always important, as it is a form of documentation. There are places where the type &lt;i&gt;is&lt;/i&gt; important, of course, when the variable is read or written in some way.&lt;/p&gt;
&lt;p&gt;Finally, static typing offers less security than at first appears. At best, it only confirms that variables of particular types are used consistently. Your unit tests also do this. However, static typing can&amp;#8217;t confirm that the &lt;i&gt;usage&lt;/i&gt; of the &lt;span class="caps"&gt;API&lt;/span&gt; is correct. This is analogous to testing the &lt;i&gt;syntax&lt;/i&gt; but not the &lt;i&gt;semantics&lt;/i&gt; of the program. In fact, only unit tests (or alternatives, like &lt;a href="http://rspec.rubyforge.org"&gt;rspec&lt;/a&gt; ) are effective at testing both.&lt;/p&gt; 
&lt;p&gt;So, it&amp;#8217;s prudent to be reticent about newer languages and features, but make sure the decisions you make about them are backed up by careful evaluation and don&amp;#8217;t forget to train your team appropriately!&lt;/p&gt;</description>
      <pubDate>Mon, 15 Jan 2007 21:57:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:bbefa294-6ed3-4a00-aa59-25b369d7c408</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2007/01/15/protecting-developers-from-powerful-languages</link>
      <category>Dean's Deprecations</category>
      <category>Java</category>
      <category>Ruby</category>
      <category>languages</category>
      <category>development</category>
    </item>
  </channel>
</rss>
