<?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: Category Design Principles</title>
    <link>http://blog.objectmentor.com/articles/category/design-principles</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>Baubles in Orbit</title>
      <description>&lt;p&gt;I have put together a nice little demonstration of the Bauble concept.  You may recall that I first wrote about it &lt;a href="http://blog.objectmentor.com/articles/2008/07/20/bauble-bauble"&gt;here&lt;/a&gt;.  Baubles are a simple component scheme for Ruby, good for when you want a component, but don&amp;#8217;t need something as heavy as a gem.&lt;/p&gt;


	&lt;p&gt;&lt;a href="http://fitnesse.org/files/unclebob/orbit.zip"&gt;orbit.zip&lt;/a&gt; contains all the files for this demonstration.  I suggest you download and unpack it.&lt;/p&gt;


	&lt;p&gt;First you need to install the Bauble gem.  Don&amp;#8217;t worry, it won&amp;#8217;t hurt anything.  Just say &lt;code&gt;gem install orbit/bauble/Bauble-0.1.gem&lt;/code&gt; (You&amp;#8217;ll probably have to do it with &lt;code&gt;sudo&lt;/code&gt;.)  That should install Bauble.  From now on you only need to say &lt;code&gt;require 'bauble'&lt;/code&gt; in your ruby scripts that make use of it.&lt;/p&gt;


Now you should be able to run the orbital simulator.  Just type:
&lt;pre&gt;&lt;code&gt;
cd orbit/MultipleBodyOrbit/lib
jruby multiple_body_orbit.rb
&lt;/code&gt;&lt;/pre&gt;
A swing window should pop up and you should be able to watch an orbital simulation.  Every run shows a different random scenario, so you can kill a lot of time by watching worlds in collision.

	&lt;p&gt;The thing to note, if you are a ruby programmer, is the use of the term &lt;code&gt;Bauble::use(-some_directory-)&lt;/code&gt;.  If you look in the &lt;code&gt;multiple_body_orbit.rb&lt;/code&gt; file you&amp;#8217;ll see I use two Baubles, the &lt;code&gt;Physics&lt;/code&gt; bauble does the raw calculation for all the gravity, forces, collisions, etc.  The &lt;code&gt;cellular_automaton&lt;/code&gt; bauble provides a very simple Swing framework for drawing dots on a screen. (Yes, this is jruby).&lt;/p&gt;


	&lt;p&gt;If you look in either of the two Baubles, you&amp;#8217;ll see that the &lt;code&gt;require&lt;/code&gt; statements within them do not know (or care) about the directory they live in.  There is none of that horrible &lt;code&gt;__FILE__&lt;/code&gt; nonsense that pollutes so many ruby scripts.  This is because the &lt;code&gt;Bauble::use&lt;/code&gt; function puts the directory path in the &lt;code&gt;LOAD_PATH&lt;/code&gt; so that subsquent &lt;code&gt;require&lt;/code&gt; statements can simply eliminate the directory spec.&lt;/p&gt;


	&lt;p&gt;Take a look at the Bauble source code.  It&amp;#8217;s no great shakes.&lt;/p&gt;


	&lt;p&gt;Also take a look at the two baubles.  They show a pretty nice way to decouple business rules from gui.  You might recognize the &lt;span class="caps"&gt;MVP&lt;/span&gt; pattern.  The &lt;code&gt;multiple_body_orbit.rb&lt;/code&gt; file contains the presenter.  Clearly the &lt;code&gt;Physics&lt;/code&gt; module is the model.  And the &lt;code&gt;cellular_automaton&lt;/code&gt; module is the view. (There is no controller, because there is no input.)&lt;/p&gt;</description>
      <pubDate>Tue, 19 Aug 2008 01:29:32 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:f2909460-a819-4cd3-93db-ec5b15b1a8cb</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/08/19/baubles-in-orbit</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Dynamic Languages</category>
      <category>Design Principles</category>
      <category>Clean Code</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>Contracts and Integration Tests for Component Interfaces</title>
      <description>&lt;p&gt;I am mentoring a team that is transitioning to XP, the first team in a planned, corporate-wide transition. Recently we ran into miscommunication problems about an interface we are providing to another team.&lt;/p&gt;


	&lt;p&gt;The problems didn&amp;#8217;t surface until a &amp;#8220;big-bang&amp;#8221; integration right before a major release, when it was too late to fix the problem. The feature was backed out of the release, as a result.&lt;/p&gt;


	&lt;p&gt;There are several lessons to take away from this experience and a few techniques for preventing these problems in the first place.&lt;/p&gt;


	&lt;p&gt;End-to-end &lt;em&gt;automated&lt;/em&gt; integration tests are a well-established way of catching these problems early on. The team I&amp;#8217;m mentoring has set up its own continuous-integration (CI) server and the team is getting pretty good at writing &lt;em&gt;acceptance&lt;/em&gt; tests using &lt;a href="http://fitnesse.org"&gt;FitNesse&lt;/a&gt;. However, these tests only cover the components provided by the team, not the true end-to-end &lt;em&gt;user stories&lt;/em&gt;. So, they are imperfect as both acceptance tests and integration tests. Our longer-term goal is to automate &lt;em&gt;true&lt;/em&gt; end-to-end acceptance and integration tests, across all components and services.&lt;/p&gt;


	&lt;p&gt;In this particular case, the other team is following a waterfall-style of development, with &lt;em&gt;big design up front&lt;/em&gt;. Therefore, my team needed to give them an interface to design against, before we were ready to actually implement the service.&lt;/p&gt;


	&lt;p&gt;There are a couple of problems with this approach. First, the two teams should really &amp;#8220;pair&amp;#8221; to work out the interface and behavior across their components. As I said, we&amp;#8217;re just starting to go Agile, but my goal is to have &lt;em&gt;virtual&lt;/em&gt; feature teams, where members of the required component teams come together as needed to implement features. This would help prevent the miscommunication of one team defining an interface and sharing it with another team through documentation, &lt;em&gt;etc.&lt;/em&gt;  Getting people to communicate face-to-face and to write code together would minimize miscommunication.&lt;/p&gt;


	&lt;p&gt;Second, defining a service interface without the implementation is risky, because it&amp;#8217;s very likely you will miss important details. The best way to work out the details of the interface is to test drive it in some way.&lt;/p&gt;


	&lt;p&gt;This suggests another technique I want to introduce to the team. When defining an interface for external consumption, don&amp;#8217;t just deliver the &amp;#8220;static&amp;#8221; interface (source files, documentation, &lt;em&gt;etc.&lt;/em&gt;), also deliver working &lt;a href="http://www.mockobjects.com/"&gt;Mock Objects&lt;/a&gt; that the other team can test against. You should develop these mocks as you test drive the interface, even if you aren&amp;#8217;t yet working on the full implementation (for schedule or other reasons).&lt;/p&gt;


	&lt;p&gt;The mocks encapsulate and enforce the behavioral &lt;strong&gt;contract&lt;/strong&gt; of the interface. &lt;a href="http://en.wikipedia.org/wiki/Design_by_contract"&gt;Design by Contract&lt;/a&gt; is a very effective way of thinking about interface design and implementing automated enforcement of it. Test-driven development mostly serves the same practical function, but thinking in &amp;#8220;contractual&amp;#8221; terms brings clarity to tests that is often missing in many of the tests I see.&lt;/p&gt;


	&lt;p&gt;Many developers already use mocks for components that don&amp;#8217;t exist yet and find that the mocks help them design the interfaces to those components, even while the mocks are being used to test clients of the components.&lt;/p&gt;


	&lt;p&gt;Of course, there is no guarantee that the mocks faithfully represent the actual behavior, but they will minimize surprises. Whether you have mocks or not, there is no substitute for running automated integration tests on real components as soon as possible.&lt;/p&gt;</description>
      <pubDate>Sun, 29 Jun 2008 21:54:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:b57496fe-d160-42bd-97cc-73608c9333d1</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/06/29/contracts-and-integration-tests-for-component-interfaces</link>
      <category>Dean's Deprecations</category>
      <category>Agile Methods</category>
      <category>Design Principles</category>
      <category>design</category>
      <category>by</category>
      <category>contract</category>
      <category>continuous</category>
      <category>integration</category>
      <category>components</category>
      <category>interfaces</category>
      <category>XP</category>
      <category>agile</category>
    </item>
    <item>
      <title>So...  You want your code to be maintainable.</title>
      <description>&lt;p&gt;We know that maintenance is 90% of the software lifecycle, and 90% of the cost.  We know that our systems need to be flexible, reusable, and maintainable.  Indeed, that&amp;#8217;s why we spend so much of our time trying to get the design and architecture just right.  Because we all know that good design and architecture is the key to flexibility, reusability, and maintainability&amp;#8230;right?&lt;/p&gt;


	&lt;p&gt;Of course.  Good design and architecture is what makes software easy to change.  Good design and architecture separates the things that change for one reason from the things that change for another reason (The Single Responsibility Principle).  Good design allows us to add new features without changing a lot of old code (Open Closed Principle).  Good design makes sure that high level policy does not depend on low level detail (Dependency Inversion Principle), etc. etc.&lt;/p&gt;


	&lt;p&gt;So how do we get good design?  Well, that&amp;#8217;s tricky.  Oh it&amp;#8217;s not too tricky to get a good design in place at first.  The tricky part is to keep the design good.   That&amp;#8217;s the problem, you see.  It&amp;#8217;s not that the design starts out so bad (although sometimes&amp;#8230;) rather it is that the design degrades over time as the system changes.&lt;/p&gt;


	&lt;p&gt;Systems change. Often they change in ways that thwart the original intent of the design.  Unfortunately, changing the design to align to these changes is &lt;em&gt;hard&lt;/em&gt;.  So we wind up hacking the new features into the system and thwarting the design.  And that&amp;#8217;s how even the best designed systems rot.&lt;/p&gt;


	&lt;p&gt;So how do we keep the design from rotting?  How do we make sure we can migrate the design as the system changes?  Simple.  Tests.&lt;/p&gt;


	&lt;p&gt;When you have a suite of tests that covers &amp;gt;90% of the code in the system, you are not afraid to make changes.  Every time you make a little change you run those tests, and you &lt;em&gt;know&lt;/em&gt; that you have not broken anything.  This gives you the confidence to make the next change, and the next, and the next.  &lt;em&gt;It gives you the confidence to change the design!&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;Nothing makes a system more flexible than a suite of tests.  Nothing.  Good architecture and design are important; but the affect of a robust suite of tests is an order of magnitude greater.  It&amp;#8217;s so much greater because those tests enable you to improve the design.&lt;/p&gt;


	&lt;p&gt;This can&amp;#8217;t be overstated.  If you want your systems to be flexible, write tests.  If you want your systems to be reusable, write tests.  If you want your systems to be maintainable, write tests.&lt;/p&gt;


	&lt;p&gt;And write your tests using the &lt;a href="http://blog.briandicroce.com/2008/03/14/three-index-cards-to-easily-remember-the-essence-of-test-driven-development/"&gt;Three Laws of &lt;span class="caps"&gt;TDD&lt;/span&gt;&lt;/a&gt;.&lt;/p&gt;</description>
      <pubDate>Tue, 24 Jun 2008 23:07:46 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:cb887e07-ff3c-4fe1-af2c-11151049fe41</guid>
      <author>Uncle Bob</author>
      <link>http://blog.objectmentor.com/articles/2008/06/24/so-you-want-your-code-to-be-maintainable</link>
      <category>Uncle Bob's Blatherings</category>
      <category>Agile Methods</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
    </item>
    <item>
      <title>Observations on Test-Driving User Interfaces</title>
      <description>&lt;p&gt;Test driving user interface development has always been a challenge. Recently, I&amp;#8217;ve worked with two projects where most of the work has been on the user-interface components.&lt;/p&gt;


	&lt;p&gt;The first project is using Adobe Flex to create a rich interface. The team decided to adopt &lt;a href="http://funfx.rubyforge.org/"&gt;FunFX&lt;/a&gt; for acceptance testing. You write your tests in Ruby, typically using &lt;a href="http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit.html"&gt;Test::Unit&lt;/a&gt; or &lt;a href="http://rspec.info/"&gt;RSpec&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;FunFX places some constraints on your Flex application. You have to define the &lt;span class="caps"&gt;GUI&lt;/span&gt; objects in &lt;span class="caps"&gt;MXML&lt;/span&gt;, the &lt;span class="caps"&gt;XML&lt;/span&gt;-based file format for Flex applications, rather than ActionScript, and you need to add ids to all elements you want to reference.[1]&lt;/p&gt;


	&lt;p&gt;These are reasonable constraints and the first constraint promotes better quality, in fact. The &lt;span class="caps"&gt;MXML&lt;/span&gt; format is more succinct (despite the &lt;span class="caps"&gt;XML&lt;/span&gt; &amp;#8220;noise&amp;#8221;) and declarative than ActionScript code. This is almost always true of UI code in most languages (with notable exceptions&amp;#8230;). Declarative &lt;em&gt;vs.&lt;/em&gt; imperative code tends to improve quality because less code means fewer bugs, less to maintain, and it frees the implementor of the declarative &amp;#8220;language&amp;#8221; to pick the best implementation strategies, optimizations, &lt;em&gt;etc.&lt;/em&gt; This characteristic is typical of Functional Languages and well-designed Domain Specific Languages, as well.&lt;/p&gt;


	&lt;p&gt;I don&amp;#8217;t think you can underestimate the benefit of writing &lt;strong&gt;less&lt;/strong&gt; code. I see too many teams whose problems would diminish considerably if they just got rid of duplication and learned to be &lt;em&gt;concise&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;The second project is a wiki-based application written in Java. To make deployment as simple as possible, the implementors avoided the Servlet &lt;span class="caps"&gt;API&lt;/span&gt; (no need to install Tomcat, &lt;em&gt;etc.&lt;/em&gt;) and rolled their own web server and page rendering components. (I&amp;#8217;m not sure I would have made these decisions myself, but I don&amp;#8217;t think they are bad, either&amp;#8230;)&lt;/p&gt;


	&lt;p&gt;The rendering components are object-oriented and use a number of design patterns, such as page factories with builder objects that reflect the &amp;#8220;widgets&amp;#8221; in the UI, &lt;span class="caps"&gt;HTML&lt;/span&gt; tags, &lt;em&gt;etc.&lt;/em&gt; This approach makes the UI very testable with JUnit and &lt;a href="http://www.fitnesse.org"&gt;FitNesse&lt;/a&gt;. In fact, the development process was a model of test-driven development.&lt;/p&gt;


	&lt;p&gt;However, the final result is flawed!  It is much too difficult to change the &lt;em&gt;look and feel&lt;/em&gt; of the application, which is essential for most UI&amp;#8217;s, especially web UI&amp;#8217;s. The project made the wrong tradeoffs; the design choices met the requirements of &lt;span class="caps"&gt;TDD&lt;/span&gt; very well, but they made maintenance and enhancement expensive and tedious. The application is now several years old and it has become dated, because of the expense of &amp;#8220;refreshing&amp;#8221; the &lt;em&gt;look and feel&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;What should have been done? These days, most dynamic web UI&amp;#8217;s are built with templating engines, of which there are many in the most common programming languages. Pages defined in a templating engine are very declarative, except for the special tags where behavior is inserted. The pages are easy to change. It is mostly obvious where a particular visual element is generated, since most of the &amp;#8220;tags&amp;#8221; in the template look exactly like the tags in the rendered page. &amp;#8220;Declarative&amp;#8221; templates, like good &lt;span class="caps"&gt;DSL&lt;/span&gt;&amp;#8217;s, can be read, understood, and even edited by the &lt;em&gt;stakeholders&lt;/em&gt;, in this case the graphical designers.&lt;/p&gt;


	&lt;p&gt;But how do you test these page templates? When test-driving UI&amp;#8217;s it is important to decide what to test and what &lt;strong&gt;not&lt;/strong&gt; to test. The general rule for &lt;span class="caps"&gt;TDD&lt;/span&gt; is to &lt;em&gt;test anything that can break&lt;/em&gt;.  The corollary, especially relevant for UI&amp;#8217;s, is &lt;em&gt;don&amp;#8217;t test anything when you don&amp;#8217;t care if it changes&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;It is usually the &lt;em&gt;dynamic behavior&lt;/em&gt; of the UI that can break and should be tested. Templating engines provide special tags for inserting dynamic behavior in the underlying language (Java, Ruby, &lt;em&gt;etc.&lt;/em&gt;). &lt;em&gt;This&lt;/em&gt; is what you should test. It is usually best to keep the &lt;em&gt;scripts&lt;/em&gt; in these tags as small as possible; the scripts just delegate to code, which can be test-driven in the usual way.&lt;/p&gt;


	&lt;p&gt;I see too many UI tests that compare long strings of &lt;span class="caps"&gt;HTML&lt;/span&gt;. These tests break whenever someone makes a minor &lt;em&gt;look and feel&lt;/em&gt; or other inconsequential change. Part of the art of &lt;span class="caps"&gt;UI TDD&lt;/span&gt; is knowing how to test just what can break and nothing more. In the second project, incidental changes to the UI break tests that should be &lt;em&gt;agnostic&lt;/em&gt; to such changes.&lt;/p&gt;


	&lt;p&gt;To conclude, keep your UI&amp;#8217;s as &lt;em&gt;declarative&lt;/em&gt; as you can. Only test the &amp;#8220;declarations&amp;#8221; (&lt;i&gt;e.g.&lt;/i&gt;, templates) in areas where they might &lt;em&gt;break&lt;/em&gt;, meaning if it changes, it&amp;#8217;s a bug. You&amp;#8217;ll get the full benefits of &lt;span class="caps"&gt;TDD&lt;/span&gt; and the freedom to change the UI easily and frequently, as needed.&lt;/p&gt;


	&lt;p id="fn1"&gt;&lt;sup&gt;1&lt;/sup&gt; Disclaimer: my information on FunFX is second hand, so I might not have the details exactly correct; see the &lt;a href="http://funfx.rubyforge.org/"&gt;FunFX&lt;/a&gt; documentation for details.&lt;/p&gt;</description>
      <pubDate>Sun, 22 Jun 2008 16:52:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:107f8948-2e28-48d7-a495-85d56801b376</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/06/22/observations-on-test-driving-user-interfaces</link>
      <category>Dean's Deprecations</category>
      <category>Testing GUIs</category>
      <category>Design Principles</category>
      <category>TDD</category>
      <category>gui</category>
      <category>declarative</category>
      <category>functional</category>
      <category>design</category>
    </item>
    <item>
      <title> What We Can Learn from the Ojibwe Language</title>
      <description>&lt;p&gt;Ojibwe (sometimes spelled Ojibwa; the last syllable is pronounced &amp;#8220;way&amp;#8221;) is one of the few Native American languages that isn&amp;#8217;t immediately threatened with extinction. It is spoken by about 10,000 people around the Great Lakes region. Brothers David and Anton Treuer are helping to keep it alive, as they discussed in a recent &lt;a href="http://www.npr.org/templates/story/story.php?storyId=89851668"&gt;Fresh Air interview&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;Ojibwe is a language that is optimized for an aboriginal people whose lives and livelihoods depend on an intimate awareness of their environment, especially the weather and water conditions. They have many nouns and verbs for fine gradations of rain, snow, ice conditions, the way water waves look and sound, &lt;em&gt;etc&lt;/em&gt;. You would want this clarity of detail if you ventured out on a lake every day to fish for dinner.&lt;/p&gt;


	&lt;p&gt;In the past, speaking languages like Ojibwe was actively suppressed by the government, in an attempt to assimilate Native Americans. Today, the threat of extinction is more from the sheer ubiquity of English. I think there is another force at play, too. People living a modern, so-called &amp;#8220;developed&amp;#8221; lifestyle just don&amp;#8217;t need to be so aware of their environment anymore. In fact, most of us are pretty &amp;#8220;tone deaf&amp;#8221; to the nuances of weather and water, which is sad in a way. We just don&amp;#8217;t perceive the need for the richness of an Ojibwe to communicate what&amp;#8217;s important to us, like sports trivia and fashion tips.&lt;/p&gt;


	&lt;p&gt;So, what does Ojibwe have to do with programming languages? Our language choices inform the way we frame problem solving and design. I was reminded of this recently while reading Ted Neward&amp;#8217;s &lt;a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=scala+neward"&gt;series of articles on Scala&lt;/a&gt;. Scala is a &lt;span class="caps"&gt;JVM&lt;/span&gt; language that provides first-class support for &lt;a href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional programming&lt;/a&gt; and object-oriented design refinements like &lt;a href="http://www.iam.unibe.ch/~scg/Research/Traits/"&gt;traits&lt;/a&gt;, which provide &lt;a href="http://c2.com/cgi/wiki?MixIn"&gt;mixin&lt;/a&gt; behavior.&lt;/p&gt;


	&lt;p&gt;While you can write Java-like code in Scala, Neward demonstrates how exploiting Scala features can result in very different code for many problems. The Scala examples are simpler, but sometimes that simplicity only becomes apparent after you grasp the underlying design principle in use, like closures or functional idioms.&lt;/p&gt;


	&lt;p&gt;One of the best pieces of advice in the &lt;a href="http://www.pragprog.com/the-pragmatic-programmer"&gt;Pragmatic Programmer&lt;/a&gt; is to learn a new language every year. You should pick a language that is very different from what you know already, not one that is fundamentally similar. Even if you won&amp;#8217;t use that language in your professional work, understanding its principles, patterns, and idioms will inform your work in whatever languages you actually use.&lt;/p&gt;


	&lt;p&gt;For example, there is a lot of &lt;a href="http://www.technologyreview.com/Infotech/17682/page1/"&gt;fretting&lt;/a&gt; these days about concurrent programming, given the rise of multi-core CPUs and multiprocessor computers.  We know &lt;a href="http://www.javaconcurrencyinpractice.com/"&gt;how to write concurrent programs&lt;/a&gt; in our most popular &lt;em&gt;imperative&lt;/em&gt; languages, like Java and C++, but that knowledge is somewhat specialized and not widely known in the community. This is the main reason that &lt;a href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional programming&lt;/a&gt; is suddenly interesting again. It is inherently easier to write concurrent applications using side-effect-free code. I expect that we will fail to meet the concurrency challenge if we rely exclusively on the mechanisms in our imperative languages.&lt;/p&gt;


	&lt;p&gt;So, you could adopt a functional language for all or part of your concurrent application. Or, if you can&amp;#8217;t use Scala (or Haskell or Erlang or &amp;#8230;) you could at least apply functional idioms, like  side-effect-free functions, avoidance of mutable objects, &lt;em&gt;etc.&lt;/em&gt; in your current imperative language. However, even that won&amp;#8217;t be an option unless you understand those principles in the first place.&lt;/p&gt;


	&lt;p&gt;Learning a new language is more than learning a new vocabulary. It&amp;#8217;s even more than learning new design techniques. It&amp;#8217;s also learning to see common things from a fresh perspective, with greater clarity.&lt;/p&gt;</description>
      <pubDate>Sat, 03 May 2008 09:48:57 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:d5cda248-84da-418d-81ae-5419241465a0</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/05/03/what-we-can-learn-from-the-ojibwe-language</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>languages</category>
      <category>polyglot</category>
      <category>programming</category>
      <category>multilingual</category>
      <category>design</category>
    </item>
    <item>
      <title>The Post-it&#194;&#174; Notes Test for UML Diagrams</title>
      <description>&lt;p&gt;A lot of teams require their developers to document their designs in &lt;span class="caps"&gt;UML&lt;/span&gt;, using Visio or another tool, before they can start coding.&lt;/p&gt;


	&lt;p&gt;Of course, this is not at all Agile. For one thing, the design is likely to change quite a bit as you learn while coding. Hardly anyone returns to the diagrams and updates them. Now they are &lt;em&gt;lies&lt;/em&gt;, because they make claims about the designs that aren&amp;#8217;t true.&lt;/p&gt;


	&lt;p&gt;&lt;span class="caps"&gt;UML&lt;/span&gt; still has a place in agile projects, of course. It&amp;#8217;s a great tool for brainstorming design ideas. So, how do you decide when a diagram is worth keeping and therefore, worth maintaining? Here&amp;#8217;s a little strategy that I recommend.&lt;/p&gt;


	&lt;p&gt;Draw the diagram during those brainstorming sessions on a white board or a poster-sized Post-it&amp;reg; Note. Drawing it this way means you have invested almost no additional effort, beyond the brainstorming itself, to create the diagram. Also, you won&amp;#8217;t feel bad about lost work if you eventually throw it away.&lt;/p&gt;


	&lt;p&gt;Leave the diagram on the wall for everyone to see while they implement the design.&lt;/p&gt;


	&lt;p&gt;By the time the note is falling off the wall or the dry-erase marker is wearing off the white board, you&amp;#8217;ll know if the ideas are still relevant or completely obsolete.&lt;/p&gt;


	&lt;p&gt;If they are obsolete, you can erase the board or toss the paper. If they are still relevant, and probably changed somewhat, you now know that the diagram is worth preserving. Go ahead and spend the time to create an updated, more permanent version in your drawing tool (but don&amp;#8217;t spend too much time!).&lt;/p&gt;</description>
      <pubDate>Tue, 22 Jan 2008 15:58:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:de899b11-fd88-4157-965b-f36aa7682fdd</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/01/22/the-post-it-reg-notes-test-for-uml-diagrams</link>
      <category>Agile Methods</category>
      <category>Design Principles</category>
      <category>design</category>
      <category>UML</category>
    </item>
    <item>
      <title>TDD for AspectJ Aspects</title>
      <description>&lt;p&gt;There was a query on the &lt;span class="caps"&gt;TDD&lt;/span&gt; mailing list about how to test drive aspects. Here is an edited version of my reply to that list.&lt;/p&gt;


	&lt;p&gt;Just as for regular classes, &lt;span class="caps"&gt;TDD&lt;/span&gt; can drive aspects to a better design.&lt;/p&gt;


	&lt;p&gt;Assume that I&amp;#8217;m testing a logging aspect that logs when certain methods are called. Here&amp;#8217;s the JUnit 4 test:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;package logging;
import static org.junit.Assert.*;
import org.junit.Test;
import app.TestApp;

public class LoggerTest {
    @Test
    public void FakeLoggerShouldBeCalledForAllMethodsOnTestClasses() {
        String message = "hello!";
        new TestApp().doFirst(message);
        assertTrue(FakeLogger.messageReceived().contains(message));
        String message2 = "World!";
        new TestApp().doSecond(message, message2);
        assertTrue(FakeLogger.messageReceived().contains(message));
    }
}
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Already, you might guess that &lt;code&gt;FakeLogger&lt;/code&gt; will be a test-only version of something, in this case, my logging aspect. Similarly, &lt;code&gt;TestApp&lt;/code&gt; is a simple class that I&amp;#8217;m using only for testing. You might choose to use one or more production classes, though.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;package app;
@Watchable
public class TestApp {
    public void doFirst(String message) {}
    public void doSecond(String message1, String message2) {}
}
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;and &lt;code&gt;@Watchable&lt;/code&gt; is a marker annotation that allows me to define pointcuts in my logger aspect without fragile coupling to concrete names, etc. You could also use an interface.&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;package app;
public @interface Watchable {}
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;I made up &lt;code&gt;@Watchable&lt;/code&gt; as a way of marking classes where the public methods might be of &amp;#8220;interest&amp;#8221; to particular observers of some kind. It&amp;#8217;s analogous to the &lt;span class="caps"&gt;EJB 3&lt;/span&gt; annotations that mark classes as &amp;#8220;persistable&amp;#8221; without implying too many details of what that might mean.&lt;/p&gt;


	&lt;p&gt;Now, the actual logging is divided into an abstract base aspect and a test-only concrete &lt;a href="&lt;/p"&gt;sub-aspect&lt;/a&gt;&amp;gt;


&lt;pre&gt;&lt;code&gt;package logging;

import org.aspectj.lang.JoinPoint;
import app.Watchable;

abstract public aspect AbstractLogger {
    // Limit the scope to the packages and types you care about.
    public abstract pointcut scope();

    // Define how messages are actually logged.
    public abstract void logMessage(String message);

    // Notice the coupling is to the @Watchable abstraction.
    pointcut watch(Object object):
        scope() &amp;#38;&amp;#38; call(* (@Watchable *).*(..)) &amp;#38;&amp;#38; target(object);

    before(Object watchable): watch(watchable) {
        logMessage(makeLogMessage(thisJoinPoint));
    }

    public static String makeLogMessage(JoinPoint joinPoint) {
        StringBuffer buff = new StringBuffer();
        buff.append(joinPoint.toString()).append(", args = ");
        for (Object arg: joinPoint.getArgs())
            buff.append(arg.toString()).append(", ");
        return buff.toString();
    }
}
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;and&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;package logging;

public aspect FakeLogger extends AbstractLogger {
    // Only match on calls from the unit tests.
    public pointcut scope(): within(logging.*Test);

    public void logMessage(String message) {
        lastMessage = message; 
    }

    static String lastMessage = null;
    public static String messageReceived() {
        return lastMessage;
    }
}
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/Pointcut"&gt;Pointcuts&lt;/a&gt; in aspects are like most other dependencies, best avoided ;) ... or at least minimized and based on abstractions, just like associations and inheritance relationships.&lt;/p&gt;


	&lt;p&gt;So, my test &amp;#8220;pressure&amp;#8221; drove the design in terms of where I needed abstraction in the Logger aspect: (i) how a message is actually logged and (ii) what classes get &amp;#8220;advised&amp;#8221; with logging behavior.&lt;/p&gt;


	&lt;p&gt;Just as for &lt;span class="caps"&gt;TDD&lt;/span&gt; of regular classes, the design ends up with minimized dependencies and flexibility (abstraction) where it&amp;#8217;s most useful.&lt;/p&gt;


	&lt;p&gt;I can now implement the real, concrete logger, which will also be a sub-aspect of &lt;code&gt;AbstractLogger&lt;/code&gt;. It will define the &lt;code&gt;scope()&lt;/code&gt; pointcut to be a larger section of the system and it will send the message to the real logging subsystem.&lt;/p&gt;</description>
      <pubDate>Tue, 02 Oct 2007 11:34:24 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:dba855da-6d02-428b-a74b-3f90ff03cdd4</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2007/10/02/tdd-for-aspectj-aspects</link>
      <category>Dean's Deprecations</category>
      <category>Agile Methods</category>
      <category>Design Principles</category>
      <category>TDD</category>
      <category>aspects</category>
      <category>AspectJ</category>
    </item>
    <item>
      <title>ANN: OOPSLA Tutorial on &amp;quot;Principles of Aspect-Oriented Design in Java and AspectJ&amp;quot;</title>
      <description>&lt;p&gt;I&amp;#8217;m doing a tutorial on aspect-oriented design principles with examples in Java and AspectJ at &lt;span class="caps"&gt;OOPSLA&lt;/span&gt; this year (October 21st). You can find a description &lt;a href="http://www.oopsla.org/oopsla2007/index.php?page=sub/&amp;#38;id=90"&gt;here&lt;/a&gt;. I believe Friday, 9/14, is the last day for early, discounted registration, so sign up now!&lt;/p&gt;


	&lt;p&gt;A short presentation on the same subject can be found &lt;a href="http://aspectprogramming.com/papers/AOPIntroAndPrinciplesTalk.pdf"&gt;here&lt;/a&gt;.&lt;/p&gt;</description>
      <pubDate>Thu, 13 Sep 2007 11:34:29 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:bf38657f-7056-46cd-bd52-5135540e5e6a</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2007/09/13/ann-oopsla-tutorial-on-principles-of-aspect-oriented-design-in-java-and-aspectj</link>
      <category>Dean's Deprecations</category>
      <category>Public Speaking Engagements</category>
      <category>Design Principles</category>
      <category>AOP</category>
      <category>design</category>
      <category>oopsla</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Are &amp;quot;else&amp;quot; blocks the root of all evil?</title>
      <description>&lt;p&gt;So, I&amp;#8217;m pair programming C++ code with a client today and he makes an observation that makes me pause.&lt;/p&gt;


	&lt;p&gt;&lt;i&gt;The well-structured, open-source code I&amp;#8217;ve looked at typically has very few &lt;code&gt;else&lt;/code&gt; blocks. You might see a conditional test with a return statement if the conditional evaluates to true, but not many &lt;code&gt;if/else&lt;/code&gt; blocks. 
&lt;/i&gt;&lt;/p&gt;


	&lt;p&gt;(I&amp;#8217;m quoting from memory&amp;#8230;) Now, this may seem crazy at first, but one of the principles we teach at Object Mentor is the &lt;a href="http://www.objectmentor.com/resources/articles/srp.pdf"&gt;Single Responsibility Principle&lt;/a&gt;, which states that a class should have only one reason to change. This principle also applies to methods. More loosely defined, a class or method should do only one thing.&lt;/p&gt;


	&lt;p&gt;So, if a method has an if/else block, is it doing two (or more) things and therefore violating the &lt;span class="caps"&gt;SRP&lt;/span&gt;?&lt;/p&gt;


	&lt;p&gt;Okay, so this is a bit too restrictive (and the title was a bit of an attention grabber&amp;#8230; ;). We&amp;#8217;re not talking about something &lt;i&gt;really&lt;/i&gt; evil, like &lt;a href="http://www.cookcomputing.com/blog/archives/000084.html"&gt;premature optimization&lt;/a&gt;, after all!&lt;/p&gt;


	&lt;p&gt;However, look at your own &lt;code&gt;if/else&lt;/code&gt; blocks and ask yourself if maybe your code would express its intent better if you refactored it to eliminate some of those &lt;code&gt;else&lt;/code&gt; blocks.&lt;/p&gt;


	&lt;p&gt;So, is there something to this idea?&lt;/p&gt;</description>
      <pubDate>Tue, 05 Jun 2007 14:42:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:ed9210a9-bfd3-4fec-b086-29ba4e1e9b77</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2007/06/05/are-else-blocks-the-root-of-all-evil</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>design</category>
      <category>SRP</category>
      <category>else</category>
      <category>blocks</category>
    </item>
    <item>
      <title>AOP and Dynamic Languages: Contradiction in Terms or Match Made in Heaven?</title>
      <description>&lt;p&gt;Consider this &lt;a href="c2.com/cgi/wiki?AspectsAndDynamicLanguages"&gt;quote&lt;/a&gt; from Dave Thomas (of the Pragmatic Programmers) on AOP (aspect-oriented programming, a.k.a. aspect-oriented software development - AOSD) :&lt;/p&gt;
&lt;blockquote&gt;Once you have decent reflection and metaclasses, AOP is 
just part of the language.&lt;/blockquote&gt;
&lt;p&gt;People who work with dynamic languages don't see any need for AOP-specific facilities in their language. They don't necessarily dispute the value of AOP for Java, where metaprogramming facilities are weaker, but for them, AOP is just a constrained form of metaprogramming. Are they right?&lt;/p&gt;


&lt;p&gt;It's easy to see why people feel this way when you consider that most of the applications of AOP have been to solve obvious "cross-cutting concerns" (CCCs) like object-relational mapping, transactions, security, &lt;i&gt;etc.&lt;/i&gt; In other words, AOP looks like just one of many tools in your toolbox to solve a particular group of problems.&lt;/p&gt;
&lt;p&gt;I'll use Ruby as my example dynamic language, since Ruby is the example I know best. It's interesting to look at Ruby on Rails source code, where you find a lot of "AOP-like" code that addresses the CCCs I just mentioned (and more). This is easy enough to do using Ruby's metaprogramming tools, even though tooling that supports AOP &lt;i&gt;semantics&lt;/i&gt; would probably make this code easier to write and maintain.&lt;/p&gt;
&lt;p&gt;This is going to be a long blog entry already, so I won't cite detailed examples here, but consider how Rails uses &lt;code&gt;method_missing&lt;/code&gt; to effectively "introduce" new methods into classes and modules. For example, in &lt;a href="http://wiki.rubyonrails.com/rails/pages/ActiveRecord"&gt;ActiveRecord&lt;/a&gt;, the many possible &lt;code&gt;find&lt;/code&gt; methods and attribute read/write methods are "implemented" this way.&lt;/p&gt;
&lt;p&gt;By the way, another excellent Ruby framework, &lt;a href="http://rspec.rubyforge.org/"&gt;RSpec&lt;/a&gt; used &lt;code&gt;method_missing&lt;/code&gt; for similar purposes, but recently refactored its implementation and public API to avoid &lt;code&gt;method_missing&lt;/code&gt;, because having multiple frameworks attempt to use the same "hook" proved very fragile!&lt;/p&gt;
&lt;p&gt;Also in Rails, method "aliasing" is done approximately 175 times, often to wrap ("advise") methods with new behaviors.&lt;/p&gt;
&lt;p&gt;Still, is there &lt;i&gt;really&lt;/i&gt; a need for AOP tooling in dynamic languages? First, consider that in the early days of OOP, some of us "faked" OOP using whatever constructs our languages provided. I wrote plenty of C code that used &lt;code&gt;struct&lt;/code&gt;s as objects and method pointers to simulate method overloading and overriding. However, few people would argue today that such an approach is "good enough". If we're thinking in objects, it sure helps to have a language that matches those semantics.&lt;/p&gt;
&lt;p&gt;Similarly, it's true that you can implement AOP using sufficiently powerful metaprogramming facilities, but it's a lot harder than having native AOP semantics in your language (or at least a close approximation thereof in libraries and their &lt;a href="http://en.wikipedia.org/wiki/Domain-specific_programming_language"&gt;DSLs&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Before proceeding, let me remind you what AOP is for in the first place. AOP is essentially a new approach to modularization that complements other approaches, like objects. It tries to solve a group of problems that other modularity approaches can't handle, namely the fine-grained interaction of multiple domain models that is required to implement required functionality.&lt;/p&gt;
&lt;p&gt;Take the classic example of security management. Presumably, you have one strategy and implementation for handling authentication and authorization. This is one domain and your application's "core business logic" is another domain.&lt;/p&gt;
&lt;p&gt;In a non-AOP system, it is necessary to insert duplicate or nearly duplicate code throughout the system that invokes the security subsystem. This duplication violates &lt;a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself"&gt;DRY&lt;/a&gt;, it clutters the logic of the code where it is inserted, it is difficult to test, maintain, replace with a new implementation, &lt;i&gt;etc.&lt;/i&gt;&lt;/p&gt;
&lt;p&gt;Now you may say that you handle this through a Spring XML configuration file or an EJB deployment configuration file, for example. Congratulations, you are using an AOP or AOP-like system!&lt;/p&gt;
&lt;p&gt;What AOP seeks to do is to allow you to specify that repeated behavior in one place, in a modular way.&lt;/p&gt;
&lt;p&gt;There are four pieces required for an AOP system:&lt;/p&gt;
&lt;h4&gt;1. Interception&lt;/h4&gt;
&lt;p&gt;You need to be able to "intercept" execution points in the program. We call these &lt;a href="http://www.eclipse.org/aspectj/doc/released/progguide/language-joinPoints.html"&gt;join points&lt;/a&gt; in the AOP jargon and sets of them that the aspect writer wants to work with at once are called &lt;a href="http://www.eclipse.org/aspectj/doc/released/progguide/language-joinPoints.html"&gt;pointcuts&lt;/a&gt; (yes, no whitespace). At each join point, &lt;a href="http://www.eclipse.org/aspectj/doc/released/progguide/language-advice.html"&gt;advice&lt;/a&gt; is the executable code that an aspect invokes either before, after or both before and after ("around") the join point.&lt;/p&gt;
&lt;p&gt;Note that the most powerful AOP language, AspectJ, let's you advise join points like instance variable reads and writes, class initialization, instance creation, &lt;i&gt;etc.&lt;/i&gt; The easiest join points to advise are method calls and many AOP systems limit themselves to this capability.&lt;/p&gt;
&lt;h4&gt;2. Introduction&lt;/h4&gt;
&lt;p&gt;Introduction is the ability to add new state and behavior to an existing class, object, &lt;i&gt;etc.&lt;/i&gt; For example, if you want to use the Observer pattern with a particular class, you could use an aspect to introduce the logic to maintain the list of observers and to notify them when state changes occur.&lt;/p&gt;
&lt;h4&gt;3. Inspection&lt;/h4&gt;
&lt;p&gt;We need to be able to find the join points of interest, either through static or runtime analysis, preferably both! You would also like to specify certain conditions of interest, which I'll discuss shortly.&lt;/p&gt;
&lt;h4&gt;4. Modularization&lt;/h4&gt;
&lt;p&gt;If we can't package all this into a "module", then we don't have a new modularization scheme. Note that a part of this modularization is the ability to somehow specify in one place the behavior I want and have it affect the entire system. Hence, AOP is a modularity system with nonlocal effects.&lt;/p&gt;
&lt;br/&gt;
&lt;p&gt;Okay. How does pure Ruby stack up these requirements? If you're a Java programmer, the idea of Interception and Introduction, where you add new state and behavior to a class, may seem radical. In languages with "open classes" like Ruby, it is trivial and common to reopen a class (or Module) and insert new attributes (state) and methods (behavior). You can even change previously defined methods. Hence, Interception and Introduction are trivial in Ruby.&lt;/p&gt;
&lt;p&gt;This is why Ruby programmers assume that AOP is nothing special, but what they are missing are the complete picture for Inspection and Modularization, even though both are partially covered.&lt;/p&gt;
&lt;p&gt;There is a rich reflection API for finding classes and objects. You can write straightforward code that searches for classes that "respond to" a particular method, for example. What you can't do easily is query based on state. For example, in AspectJ, you can say, "I want to advise method call X.m when it is called in the context flow ('&lt;code&gt;cflow&lt;/code&gt;') of method call Y.m2 somewhere up the stack..." Yes, you can figure out how to do this in Ruby, but it's hard. So, we're back to the argument I made earlier that you would really like your language to match the semantics of your ideas.&lt;/p&gt;
&lt;p&gt;For modularization, yes you can put all the aspect-like code in a Module or Class. The hard part is encapsulating any complicated "point cut" metaprogramming in one place, should you want to use it again later. That is, once you figure out how to do the &lt;code&gt;cflow&lt;/code&gt; pointcuts using metaprogramming, you'll want that tricky bit of code in a library somewhere.&lt;/p&gt;
&lt;p&gt;At this point, you might be saying to yourself, "Okay, so it might be nice to have some AOP stuff in Ruby, but the Rails guys seem to be doing okay without it. Is it &lt;i&gt;really&lt;/i&gt; worth the trouble having AOP in the language?" Only if AOP is more applicable than for the limited set of problems described previously.&lt;/p&gt;
&lt;h4&gt;Future Applications of AOP??&lt;/h4&gt;
&lt;p&gt;Here's what I've been thinking about lately. Ruby is a wonderful language for creating mini-&lt;a href="http://en.wikipedia.org/wiki/Domain-specific_programming_language"&gt;DSLs&lt;/a&gt;. The &lt;a href="http://wiki.rubyonrails.com/rails/pages/ActiveRecord"&gt;ActiveRecord&lt;/a&gt; DSL is a good example. It provides relational semantics, while the library minimizes the coding required by the developer. (AR reads the database schema and builds an in-memory representation of the records as objects.)&lt;/p&gt;
&lt;p&gt;Similarly, there is a lot of emphasis these days on development that centers around the &lt;a href="http://domaindrivendesign.org/books/index.html"&gt;domain&lt;/a&gt; or &lt;a href="http://en.wikipedia.org/wiki/Feature_Driven_Development"&gt;features&lt;/a&gt; of the project. Recall that I said that AOP is about modularizing the intersection of multiple domains (and recall my previous &lt;a href="http://blog.objectmentor.com/articles/trackback/4765"&gt;blog&lt;/a&gt; on the AOSD 2007 Conference where Gerald Sussman remarked that successful systems have more than one organizing principle).&lt;/p&gt;
&lt;p&gt;I think we'll see AOP become the underlying implementation of powerful DSLs that allow programmers who are &lt;i&gt;not&lt;/i&gt; AOP-literate express cross-cutting concerns in domain-specific and intuitive languages. AOP will do the heavy lifting behind the scenes to make the fine-grained interactions work. I really don't expect a majority of developers to become AOP literate any time soon. In my experience, too many so-called developers don't get objects. They'll never master aspects!&lt;/p&gt;
&lt;h4&gt;Shameless Plug&lt;/h4&gt;
&lt;p&gt;If you would like to hear more of my ideas about AOP in Ruby and aspect-oriented design (AOD), please come to my &lt;a href="https://www.cmpevents.com/SDw7/a.asp?option=G&amp;amp;V=3&amp;amp;id=447368"&gt;talk&lt;/a&gt; at SD West, this Friday at 3:30. I'm also giving a &lt;a href="http://web4.cs.ucl.ac.uk/icse07/index.php?id=90"&gt;full-day tutorial&lt;/a&gt; on AOD in Ruby and Java/AspectJ at the ICSE 2007 conference in Minneapolis, May 26th.&lt;/p&gt;</description>
      <pubDate>Wed, 21 Mar 2007 13:21:35 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:3cf85795-7574-4b92-89a5-49b78f80f4ce</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2007/03/21/aop-and-dynamic-languages-contradiction-in-terms-or-match-made-in-heaven</link>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>Design Principles</category>
      <category>design</category>
      <category>AOP</category>
      <category>AOD</category>
      <category>Ruby</category>
      <category>Dynamic Languages</category>
      <trackback:ping>http://blog.objectmentor.com/articles/trackback/5268</trackback:ping>
    </item>
    <item>
      <title>Liskov Substitution Principle and the Ruby Core Libraries</title>
      <description>&lt;p&gt;There is a spirited discussion happening now on the ruby-talk list called &lt;a href="http://www.ruby-forum.com/topic/97965&lt;a href="""&gt;&amp;gt;Oppinions on &lt;span class="caps"&gt;RCR&lt;/span&gt; for dup on immutable classes&lt;/a&gt; (sic).&lt;/p&gt;


	&lt;p&gt;In the core Ruby classes, the &lt;code&gt;Kernel&lt;/code&gt; module, which is the root of everything, even &lt;code&gt;Object&lt;/code&gt;, defines a method called &lt;code&gt;dup&lt;/code&gt;, for duplicating objects. (There is also a &lt;code&gt;clone&lt;/code&gt; method with slightly different behavior that I won&amp;#8217;t discuss here.)&lt;/p&gt;


	&lt;p&gt;The problem is that some derived core classes throw an exception when &lt;code&gt;dup&lt;/code&gt; is called.&lt;/p&gt;


Specifically, as the ruby-talk discussion title says, it&amp;#8217;s the &lt;em&gt;immutable&lt;/em&gt; classes (&lt;code&gt;NilClass, FalseClass, TrueClass, Fixnum,&lt;/code&gt; and &lt;code&gt;Symbol&lt;/code&gt;) that do this. Consider, for example, the following &lt;strong&gt;irb&lt;/strong&gt; session: 
&lt;pre&gt;
irb 1:0&amp;gt; 5.respond_to? :dup
=&amp;gt; true
irb 2:0&amp;gt; 5.dup
TypeError: can't dup Fixnum
        from (irb):1:in `dup'
        from (irb):1
irb 3:0&amp;gt; 
&lt;/pre&gt;
If you don&amp;#8217;t know Ruby, the first line asks the &lt;code&gt;Fixnum&lt;/code&gt; object &lt;code&gt;5&lt;/code&gt; if it &lt;em&gt;responds to&lt;/em&gt; the method &lt;code&gt;dup&lt;/code&gt; (with the name expressed as a symbol, hence the&lt;/a&gt;). The answer is true, becuase this method is defined by the module &lt;code&gt;Kernel&lt;/code&gt;, which is included by the top-level class &lt;code&gt;Object&lt;/code&gt;, an ancestor of &lt;code&gt;Fixnum&lt;/code&gt;.

	&lt;p&gt;However, when you actually call &lt;code&gt;dup&lt;/code&gt; on &lt;code&gt;5&lt;/code&gt;, it raises &lt;code&gt;TypeError&lt;/code&gt;, as shown.&lt;/p&gt;


	&lt;p&gt;So, this looks like a classic &lt;a href="http://www.objectmentor.com/resources/articles/lsp.pdf"&gt;Liskov Substitution Principle&lt;/a&gt; violation. The term for this code smell is &lt;em&gt;Refused Bequest&lt;/em&gt; (&lt;em&gt;e.g.,&lt;/em&gt; see &lt;a href="http://www.soberit.hut.fi/mmantyla/BadCodeSmellsTaxonomy.htm"&gt;here&lt;/a&gt;) and it&amp;#8217;s typically fixed with the &lt;em&gt;refactoring&lt;/em&gt; &lt;a href="http://www.refactoring.com/catalog/replaceInheritanceWithDelegation.html"&gt;Replace Inheritance with Delegation&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;The email thread is about a proposal to change the library in one of several possible ways. One possibility is to remove &lt;code&gt;dup&lt;/code&gt; from the &lt;em&gt;immutable&lt;/em&gt; classes. This would eliminate the unexpected behavior in the example above, since &lt;code&gt;5.respond_to?(:dup)&lt;/code&gt; would return false, but it would still be an &lt;span class="caps"&gt;LSP&lt;/span&gt; violation, specifically it would still have the &lt;em&gt;Refused Bequest&lt;/em&gt; smell.&lt;/p&gt;


	&lt;p&gt;One scenario where the current behavior causes problems is doing a deep copy of an arbitrary object graph. For immutable objects, you would normally just want &lt;code&gt;dup&lt;/code&gt; to return the same object. It&amp;#8217;s immutable, right? Well, not exactly, since you can re-open classes and even objects to add and remove methods in Ruby (there are some limitations for the immutables&amp;#8230;).  So, if you thought you actually duplicated something and started messing with its methods, you would be surprised to find the original was &amp;#8220;also&amp;#8221; modified.&lt;/p&gt;


	&lt;p&gt;So, how serious is this &lt;span class="caps"&gt;LSP&lt;/span&gt; issue (one of several)? When I pointed out the problem in the discussion, one respondent, Robert Dober, said the following (edited slightly):&lt;/p&gt;


	&lt;p&gt;&lt;i&gt;
I would say that &lt;span class="caps"&gt;LSP&lt;/span&gt; does not apply here simply because in Ruby we do
not have that kind of contract. In order to apply &lt;span class="caps"&gt;LSP&lt;/span&gt; we need to say at a point we have an object of class &lt;code&gt;Base&lt;/code&gt;, for example. (let the gods forgive me that I use Java)&lt;/i&gt;
&lt;pre&gt;
void aMethod(final Base b){
   ....
}
&lt;/pre&gt;
&lt;i&gt;and we expect this to work whenever we call aMethod with an object
that is a Base.
Anyway the compiler would not really allow otherwise.&lt;/i&gt;
&lt;pre&gt;
SubClass sc;  // subclassing Base od course
aMethod( sc ); // this is expected to work (from the type POV).
&lt;/pre&gt;&lt;/p&gt;


	&lt;p&gt;&lt;i&gt;Such things just do not exist in Ruby, I believe that Ruby has
explained something to me:&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;OO Languages are Class oriented languages&lt;/li&gt;
		&lt;li&gt;Dynamic Languages are Object oriented languages.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;Replace Class with Type and you see what I mean.&lt;/p&gt;


	&lt;p&gt;This is all very much &lt;span class="caps"&gt;IMHO&lt;/span&gt; of course but I feel that the Ruby
community has made me evolve a lot away from &amp;#8220;Class oriented&amp;#8221;.&lt;/i&gt;&lt;/p&gt;


	&lt;p&gt;He&amp;#8217;s wrong that the compiler protects you in Java; you can still throw exceptions, &lt;em&gt;etc.&lt;/em&gt; The &lt;span class="caps"&gt;JDK&lt;/span&gt; Collection classes have &lt;em&gt;Refused Bequests&lt;/em&gt;. Besides that, however, he makes some interesting points.&lt;/p&gt;


	&lt;p&gt;As a long-time Java programmer, I&amp;#8217;m instinctively uncomfortable with &lt;span class="caps"&gt;LSP&lt;/span&gt; violations. Yet, the Ruby &lt;span class="caps"&gt;API&lt;/span&gt; is very nice to work with, so maybe a little &lt;span class="caps"&gt;LSP&lt;/span&gt; violation isn&amp;#8217;t so bad?&lt;/p&gt;


	&lt;p&gt;As Robert says, we approach our designs differently in dynamic &lt;em&gt;vs.&lt;/em&gt; static languages. In Ruby, you almost never use the &lt;code&gt;is_a?&lt;/code&gt; and &lt;code&gt;kind_of?&lt;/code&gt; methods to check for type. Instead, you follow the &lt;em&gt;duck typing&lt;/em&gt; philosophy (&amp;#8220;If it acts like a duck, it must be a duck&amp;#8221;); you rely on &lt;code&gt;respond_to?&lt;/code&gt; to decide if an object does what you want.&lt;/p&gt;


	&lt;p&gt;In the case of &lt;code&gt;dup&lt;/code&gt; for the immutable classes, I would prefer that they not implement the method, rather than throw an exception. However, that would still violate &lt;span class="caps"&gt;LSP&lt;/span&gt;.&lt;/p&gt;


	&lt;p&gt;So, can we still satisfy &lt;span class="caps"&gt;LSP&lt;/span&gt; and also have rich base classes and modules?&lt;/p&gt;


	&lt;p&gt;There are many examples of &lt;em&gt;traits&lt;/em&gt; that one object might or should support, but not another. (Those of you Java programmers might ask yourself why all objects support &lt;code&gt;toString&lt;/code&gt;, for example. Why not also &lt;code&gt;toXML&lt;/code&gt;...?)&lt;/p&gt;


	&lt;p&gt;Coming from an &lt;a href="http://aspectprogramming.com"&gt;&lt;span class="caps"&gt;AOP&lt;/span&gt;&lt;/a&gt; background, I would rather see an architecture where &lt;code&gt;dup&lt;/code&gt; is added only to those classes and modules that can support it. It shouldn&amp;#8217;t be part of the standard &amp;#8220;signature&amp;#8221; of &lt;code&gt;Kernel&lt;/code&gt;, but it should be present when code actually needs it.&lt;/p&gt;


In fact, Ruby makes this sort of &lt;span class="caps"&gt;AOP&lt;/span&gt; &lt;a href="c2.com/cgi/wiki?AspectsAndDynamicLanguages"&gt;easy&lt;/a&gt; to implement. Maybe &lt;code&gt;Kernel&lt;/code&gt;, &lt;code&gt;Module&lt;/code&gt;, and &lt;code&gt;Object&lt;/code&gt; should be refactored into smaller pieces and programmers should declaratively mixin the &lt;em&gt;traits&lt;/em&gt; they need. Imagine something like the following:
&lt;pre&gt;
irb 1:0&amp;gt; my_obj.respond_to? :dup
=&amp;gt; false
irb 2:0&amp;gt; include 'DupableTrait'  
irb 2:0&amp;gt; my_obj.respond_to? :dup
=&amp;gt; true
irb 4:0&amp;gt; def dup_if_possible items
irb 5:1&amp;gt;  items.map {|item| item.respond_to?(:dup) ? item.dup : item}
irb 6:1&amp;gt; end
...
&lt;/pre&gt;
In other words, &lt;code&gt;Kernel&lt;/code&gt; no longer &amp;#8220;exposes the &lt;code&gt;dup&lt;/code&gt; abstraction&amp;#8221;, by default, but the &lt;code&gt;DupableTrait&lt;/code&gt; module &amp;#8220;magically&amp;#8221; adds &lt;code&gt;dup&lt;/code&gt; to all the classes that can support it. This way, we preserve &lt;span class="caps"&gt;LSP&lt;/span&gt;, streamline the core classes and modules (&lt;a href="http://www.objectmentor.com/resources/articles/srp"&gt;&lt;span class="caps"&gt;SRP&lt;/span&gt;&lt;/a&gt; and &lt;a href="http://www.objectmentor.com/resources/articles/isp.pdf"&gt;&lt;span class="caps"&gt;ISP&lt;/span&gt;&lt;/a&gt; anyone?), yet we have the flexibility we need, on demand.</description>
      <pubDate>Sat, 17 Feb 2007 14:20:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:767b95e8-95d2-45dd-8aa0-09dfb4fe92ec</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2007/02/17/liskov-substitution-principle-and-the-ruby-core-libraries</link>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>Design Principles</category>
      <category>Ruby</category>
      <category>object-oriented design</category>
      <category>Liskov Substitution Principle</category>
      <category>LSP</category>
      <trackback:ping>http://blog.objectmentor.com/articles/trackback/188</trackback:ping>
    </item>
  </channel>
</rss>
