<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Object Mentor Blog: Tag Ruby</title>
    <link>http://blog.objectmentor.com/articles/tag/ruby</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>The Liskov Substitution Principle for &amp;quot;Duck-Typed&amp;quot; Languages</title>
      <description>&lt;p&gt;&lt;span class="caps"&gt;OCP&lt;/span&gt; and &lt;span class="caps"&gt;LSP&lt;/span&gt; together tell us how to organize similar &lt;em&gt;vs.&lt;/em&gt; variant behaviors. I blogged the other day about &lt;a href="http://blog.objectmentor.com/articles/2008/09/04/the-open-closed-principle-for-languages-with-open-classes"&gt;&lt;span class="caps"&gt;OCP&lt;/span&gt; in the context of languages with open classes&lt;/a&gt;
 (&lt;em&gt;i.e.,&lt;/em&gt; dynamically-typed languages). Let&amp;#8217;s look at the &lt;a href="http://www.objectmentor.com/resources/articles/lsp.pdf"&gt;Liskov Substitution Principle&lt;/a&gt; (LSP).&lt;/p&gt;


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


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


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


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


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


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


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

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


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

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

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

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


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


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


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


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


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

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

class MyTracer
  def trace message
    p message
  end
end

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

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


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


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


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


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


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

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

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

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


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


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


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


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

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

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

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

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


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


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


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


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


	&lt;p&gt;An important point is that the idea of a &amp;#8220;contract&amp;#8221; between the types and their clients is still important, even in a  language with duck-typing or structural typing. However, languages with these features give us more ways to extend our system, while still supporting &lt;span class="caps"&gt;LSP&lt;/span&gt;.&lt;/p&gt;</description>
      <pubDate>Sat, 06 Sep 2008 23:48:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:48d425c0-b536-44de-bf6a-b83755c064b9</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/09/06/the-liskov-substitution-principle-for-duck-typed-languages</link>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>Design Principles</category>
      <category>Ruby</category>
      <category>ducktyping</category>
      <category>Scala</category>
      <category>Java</category>
      <category>design</category>
      <category>LSP</category>
    </item>
    <item>
      <title>The Open-Closed Principle for Languages with Open Classes</title>
      <description>&lt;p&gt;We&amp;#8217;ve been having a discussion inside Object Mentor World Design Headquarters about the meaning of the &lt;span class="caps"&gt;OCP&lt;/span&gt; for dynamic languages, like Ruby, with open classes.&lt;/p&gt;


	&lt;p&gt;For example, in Ruby it&amp;#8217;s normal to define a class or module, &lt;em&gt;e.g.,&lt;/em&gt;&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# foo.rb
class Foo
    def method1 *args
        ...
    end
end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;and later re-open the class and add (or redefine) methods,&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# foo2.rb
class Foo
    def method2 *args
        ...
    end
end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Users of &lt;code&gt;Foo&lt;/code&gt; see all the methods, as if &lt;code&gt;Foo&lt;/code&gt; had one definition.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
foo = Foo.new
foo.method1 :arg1, :arg2
foo.method2 :arg1, :arg2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Do open classes violate the Open-Closed Principle? Bertrand Meyer articulated &lt;span class="caps"&gt;OCP&lt;/span&gt;. Here is his definition&lt;sup&gt;&lt;a href="#fn1"&gt;1&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;Software entities (classes, modules, functions, &lt;em&gt;etc.&lt;/em&gt;) should be open for extension, but closed for modification.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;He elaborated on it &lt;a href="http://se.ethz.ch/~meyer/publications/computer/implicitness.pdf"&gt;here&lt;/a&gt;.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;... This is the open-closed principle, which in my opinion is one of the central innovations of object technology: the ability to use a software component as it is, while retaining the possibility of adding to it later through inheritance. Unlike the records or structures of other approaches, a class of object technology is both closed and open: closed because we can start using it for other components (its clients); open because we can at any time add new properties without invalidating its existing clients.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;blockquote&gt;
		&lt;p&gt;&lt;a href="http://se.ethz.ch/~meyer/publications/computer/implicitness.pdf"&gt;Tell Less, Say More: The Power of Implicitness&lt;/a&gt;&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;So, if one client &lt;code&gt;require&lt;/code&gt;&amp;#8217;s only &lt;code&gt;foo.rb&lt;/code&gt; and only uses &lt;code&gt;method1&lt;/code&gt;, that client doesn&amp;#8217;t care what &lt;code&gt;foo2.rb&lt;/code&gt; does. However, if the client also &lt;code&gt;require&lt;/code&gt;&amp;#8217;s &lt;code&gt;foo2.rb&lt;/code&gt;, perhaps indirectly through another &lt;code&gt;require&lt;/code&gt;, problems will ensue unless the client is unaffected by what &lt;code&gt;foo2.rb&lt;/code&gt; does.  This looks a lot like the way &amp;#8220;good&amp;#8221; inheritance should behave.&lt;/p&gt;


	&lt;p&gt;So, the answer is &lt;em&gt;no&lt;/em&gt;, we aren&amp;#8217;t violating &lt;span class="caps"&gt;OCP&lt;/span&gt;, as long as we extend a re-opened class following the same rules we would use when inheriting from it.&lt;/p&gt;


	&lt;p&gt;If we use inheritance instead:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# foo.rb
class Foo
    def method1 *args
        ...
    end
end
...
class DerivedFoo &amp;lt; Foo
    def method2 *args
        ...
    end
end
...
foo = SubFoo.new    # Instantiate different class...
foo.method1 :arg1, :arg2
foo.method2 :arg1, :arg2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;One notable difference is that we have to instantiate a different class. This is an important difference. While you can often just use inheritance, and maybe you should prefer it, inheritance only works if you have full control over what types get instantiated and &lt;em&gt;it&amp;#8217;s easy to change which types you use&lt;/em&gt;. Of course, inheritance is also the best approach when you need all behavioral variants &lt;em&gt;simulateneously&lt;/em&gt;, &lt;em&gt;i.e.,&lt;/em&gt; each variant in one or more objects.&lt;/p&gt;


	&lt;p&gt;Sometimes you want to affect the behavior of all instances transparently, without changing the types that are instantiated. A slightly better example, logging method calls, illustrates the point. Here we use the &amp;#8220;famous&amp;#8221; &lt;code&gt;alias_method&lt;/code&gt; in Ruby.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
# foo.rb
class Foo
    def method1 *args
        ...
    end
end
# logging_foo.rb
class Foo
    alias_method :old_method1, :method1
    def method1 *args
        p "Inside method1(#{args.inspect})" 
        old_method1 *args
    end
end
...
foo = Foo.new
foo.method1 :arg1, :arg2
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;&lt;code&gt;Foo.method1&lt;/code&gt; behaves like a subclass override, with extended behavior that still obeys the &lt;a href="http://www.objectmentor.com/resources/articles/lsp.pdf"&gt;Liskov-Substitution Principle&lt;/a&gt; (LSP).&lt;/p&gt;


	&lt;p&gt;So, I think the &lt;span class="caps"&gt;OCP&lt;/span&gt; can be reworded slightly.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;Software entities (classes, modules, functions, &lt;em&gt;etc.&lt;/em&gt;) should be open for extension, but closed for &lt;strong&gt;source&lt;/strong&gt; modification.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;We should not re-open the original source, but adding functionality through a separate source file is okay.&lt;/p&gt;


	&lt;p&gt;Actually, I prefer a slightly different wording.&lt;/p&gt;


	&lt;blockquote&gt;
		&lt;p&gt;Software entities (classes, modules, functions, &lt;em&gt;etc.&lt;/em&gt;) should be open for extension, but closed for &lt;strong&gt;source and contract&lt;/strong&gt; modification.&lt;/p&gt;
	&lt;/blockquote&gt;


	&lt;p&gt;The extra &lt;strong&gt;and contract&lt;/strong&gt; is redundant with &lt;span class="caps"&gt;LSP&lt;/span&gt;. I don&amp;#8217;t think this kind of redundancy is necessarily bad. ;) The &lt;em&gt;contract&lt;/em&gt; is the set of &lt;em&gt;behavioral expectations&lt;/em&gt; between the &amp;#8220;entity&amp;#8221; and its client(s). Just as it is &lt;a href="http://blog.objectmentor.com/articles/2007/02/17/liskov-substitution-principle-and-the-ruby-core-libraries"&gt;bad to break the contract with inheritance&lt;/a&gt;, it is also bad to break it through open classes.&lt;/p&gt;


	&lt;p&gt;&lt;span class="caps"&gt;OCP&lt;/span&gt; and &lt;span class="caps"&gt;LSP&lt;/span&gt; together are our most important design principles for effective organization of similar &lt;em&gt;vs.&lt;/em&gt; variant behaviors. Inheritance is one way we do this. Open classes provide another way. Aspects provide a third way and are subject to the same &lt;a href="http://www.aosd.net/2007/program/industry/I6-AspectDesignPrinciples.pdf"&gt;design issues&lt;/a&gt;.&lt;/p&gt;


	&lt;p id="fn1"&gt;&lt;sup&gt;1&lt;/sup&gt; Meyer, Bertrand (1988). Object-Oriented Software Construction. Prentice Hall. &lt;span class="caps"&gt;ISBN 0136290493&lt;/span&gt;.&lt;/p&gt;</description>
      <pubDate>Thu, 04 Sep 2008 21:42:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:8045ef44-c256-4c10-9edf-7f9fde4a26bd</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/09/04/the-open-closed-principle-for-languages-with-open-classes</link>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>Design Principles</category>
      <category>Clean Code</category>
      <category>OCP</category>
      <category>languages</category>
      <category>Ruby</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>Unit Testing C and C++ ... with Ruby and RSpec!</title>
      <description>&lt;p&gt;If you&amp;#8217;re writing C/C&amp;#043;&amp;#043; code, it&amp;#8217;s natural to write your unit tests in the same language (or use C&amp;#043;&amp;#043; for your C test code). All the well-known unit testing tools take this approach.&lt;/p&gt;


	&lt;p&gt;I think we can agree that neither language offers the best developer productivity among all the language choices out there. Most of us use either language because of perceived performance requirements, institutional and industry tradition, &lt;em&gt;etc.&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;There&amp;#8217;s growing interest, however, in mixing languages, tools, and &lt;em&gt;paradigms&lt;/em&gt; to get the best tool for a particular job. &amp;lt;shameless-plug&amp;gt;I&amp;#8217;m giving a talk March 7&lt;sup&gt;th&lt;/sup&gt; at &lt;a href="https://www.cmpevents.com/SDw8/a.asp?option=C&amp;#38;V=11&amp;#38;SessID=6102"&gt;SD West&lt;/a&gt; on this very topic, called &lt;a href="https://www.cmpevents.com/SDw8/a.asp?option=C&amp;#38;V=11&amp;#38;SessID=6102"&gt;Polyglot and Poly-Paradigm Programming&lt;/a&gt; &amp;lt;/shameless-plug&amp;gt;.&lt;/p&gt;


	&lt;p&gt;So, why not use a more productive language for your C or C&amp;#043;&amp;#043; unit tests? You have more freedom in your development chores than what&amp;#8217;s required for production. Why not use Ruby&amp;#8217;s &lt;a href="http://rspec.info/"&gt;RSpec&lt;/a&gt;, a &lt;a href="http://behaviour-driven.org/"&gt;Behavior-Driven Development&lt;/a&gt; tool for acceptance and unit testing? Or, you could use Ruby&amp;#8217;s version of &lt;a href="http://www.junit.org"&gt;JUnit&lt;/a&gt;, called &lt;a href="http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit.html"&gt;Test::Unit&lt;/a&gt;. The hard part is integrating Ruby and C/C&amp;#043;&amp;#043;. If you&amp;#8217;ve been looking for an excuse to bring Ruby (or Tcl or Python or Java or&amp;#8230;) into your C/C&amp;#043;&amp;#043; environment, starting with development tasks is usually the path of least resistance.&lt;/p&gt;


	&lt;p&gt;I did some experimenting over the last few days to integrate &lt;a href="http://rspec.info/"&gt;RSpec&lt;/a&gt;  using &lt;a href="http://www.swig.org"&gt;&lt;span class="caps"&gt;SWIG&lt;/span&gt;&lt;/a&gt; (Simplified Wrapper and Interface Generator), a tool for bridging libraries written in C and C&amp;#043;&amp;#043; to other languages, like Ruby. The &lt;a href="http://www.swig.org/Doc1.3/Ruby.html"&gt;Ruby section&lt;/a&gt; of the &lt;span class="caps"&gt;SWIG&lt;/span&gt; manual was very helpful.&lt;/p&gt;


	&lt;h2&gt;My Proof-of-Concept Code&lt;/h2&gt;


	&lt;p&gt;Here is a zip file of my experiment: &lt;a href="http://blog.objectmentor.com/files/rspec_for_cpp.zip" title="rspec_for_cpp.zip"&gt;rspec_for_cpp.zip&lt;/a&gt;&lt;/p&gt;


	&lt;p&gt;This is far from a complete and working solution, but I think it shows promise. See the &lt;strong&gt;Current Limitations&lt;/strong&gt; section below for details.&lt;/p&gt;


	&lt;p&gt;Unzip the file into a directory. I&amp;#8217;ll assume you named it &lt;code&gt;rspec_for_cpp&lt;/code&gt;. You need to have &lt;code&gt;gmake&lt;/code&gt;, &lt;code&gt;gcc&lt;/code&gt;, &lt;span class="caps"&gt;SWIG&lt;/span&gt; and Ruby installed, along with the RSpec &amp;#8220;gem&amp;#8221;. Right now, it only builds on &lt;span class="caps"&gt;OS X&lt;/span&gt; and Linux (at least the configurations on my machines running those OS&amp;#8217;s &amp;#8211; see the discussion below). To run the build, use the following commands:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
        $ cd rspec_for_cpp/cpp
        $ make 
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;You should see it finish with the lines&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
        ( cd ../spec; spec *_spec.rb )
        .........

        Finished in 0.0***** seconds

        9 examples, 0 failures
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Congratulations, you&amp;#8217;ve just tested some C and C&amp;#043;&amp;#043; code with RSpec! (Or, if you didn&amp;#8217;t succeed, see the notes in the &lt;code&gt;Makefile&lt;/code&gt; and the discussion below.)&lt;/p&gt;


	&lt;h2&gt;The Details&lt;/h2&gt;


	&lt;p&gt;I&amp;#8217;ll briefly walk you through the files in the zip and the key steps required to make it all work.&lt;/p&gt;


	&lt;h3&gt;&lt;code&gt;cexample.h&lt;/code&gt;&lt;/h3&gt;


	&lt;p&gt;Here is a simple C header file.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
        /* cexample.h */
        #ifndef CEXAMPLE_H
        #define CEXAMPLE_H
        #ifdef __cplusplus
         extern "C" {
        #endif
        char* returnString(char* input);
        double returnDouble(int input);
        void  doNothing();

        #ifdef __cplusplus
         }
        #endif
        #endif
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Of course, in a pure C shop, you won&amp;#8217;t need the &lt;code&gt;#ifdef __cplusplus&lt;/code&gt; stuff. I found this was essential in my experiment when I mixed C and C&amp;#043;&amp;#043;, as you might expect.&lt;/p&gt;


	&lt;h3&gt;&lt;code&gt;cpp/cexample.c&lt;/code&gt;&lt;/h3&gt;


	&lt;p&gt;Here is the corresponding C source file.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
        /* cexample.h */

        char* returnString(char* input) {
            return input;
        }

        double returnDouble(int input) {
            return (double) input;
        }

        void  doNothing() {}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;h3&gt;&lt;code&gt;cpp/CppExample.h&lt;/code&gt;&lt;/h3&gt;


	&lt;p&gt;Here is a C&amp;#043;&amp;#043; header file.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
        #ifndef CPPEXAMPLE_H
        #define CPPEXAMPLE_H

        #include &amp;lt;string&amp;gt;

        class CppExample 
        {
        public:
            CppExample();
            CppExample(const CppExample&amp;#38; foo);
            CppExample(const char* title, int flag);
            virtual ~CppExample();

            const char* title() const;
            void        title(const char* title);
            int         flag() const;
            void        flag(int value);

            static int countOfCppExamples();
        private:
            std::string _title;
            int         _flag;
        };

        #endif
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;h3&gt;&lt;code&gt;cpp/CppExample.cpp&lt;/code&gt;&lt;/h3&gt;


	&lt;p&gt;Here is the corresponding C&amp;#043;&amp;#043; source file.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
        #include "CppExample.h" 

        CppExample::CppExample() : _title("") {}
        CppExample::CppExample(const CppExample&amp;#38; foo): _title(foo._title) {}
        CppExample::CppExample(const char* title, int flag) : _title(title), _flag(flag) {}
        CppExample::~CppExample() {}

        const char* CppExample::title() const { return _title.c_str(); }
        void        CppExample::title(const char* name) { _title = name; }

        int  CppExample::flag() const { return _flag; }
        void CppExample::flag(int value) { _flag = value; }

        int CppExample::countOfCppExamples() { return 1; }
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;h3&gt;&lt;code&gt;cpp/example.i&lt;/code&gt;&lt;/h3&gt;


	&lt;p&gt;Typically in &lt;span class="caps"&gt;SWIG&lt;/span&gt;, you specify a &lt;code&gt;.i&lt;/code&gt; file to the &lt;code&gt;swig&lt;/code&gt; command to define the &lt;em&gt;module&lt;/em&gt; that wraps the classes and global functions, which classes and functions to expose to the target language (usually all in our case), and other assorted customization options, which are discussed in the &lt;a href="http://www.swig.org/Doc1.3"&gt;&lt;span class="caps"&gt;SWIG&lt;/span&gt; manual&lt;/a&gt;. I&amp;#8217;ll show the &lt;code&gt;swig&lt;/code&gt; command in a minute. For now, note that I&amp;#8217;m going to generate an &lt;code&gt;example_wrap.cpp&lt;/code&gt; file that will function as the bridge between the languages.&lt;/p&gt;


	&lt;p&gt;Here&amp;#8217;s my &lt;code&gt;example.i&lt;/code&gt;, where I named the module &lt;code&gt;example&lt;/code&gt;.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
        %module example
        %{
            #include "cexample.h" 
            #include "CppExample.h"    
        %}
        %include "cexample.h" 
        %include "CppExample.h" 
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;It looks odd to have header files appear twice. The code inside the &lt;code&gt;%{...%}&lt;/code&gt; (with a &amp;#8217;#&amp;#8217; before each &lt;code&gt;include&lt;/code&gt;) are standard C and C&amp;#043;&amp;#043; statements, &lt;em&gt;etc.&lt;/em&gt; that will be inserted verbatim into the generated &amp;#8220;wrapper&amp;#8221; file, &lt;code&gt;example_wrap.cpp&lt;/code&gt;, so that file will compile when it references anything declared in the header files. The second case, with a &amp;#8217;%&amp;#8217; before the &lt;code&gt;include&lt;/code&gt; statements&lt;sup&gt;&lt;a href="#fn1"&gt;1&lt;/a&gt;&lt;/sup&gt;, tells &lt;span class="caps"&gt;SWIG&lt;/span&gt; to make all the declarations in those header files available to the target language. (You can be more selective, if you prefer&amp;#8230;)&lt;/p&gt;


	&lt;p&gt;Following Ruby conventions, the Ruby plugin for &lt;span class="caps"&gt;SWIG&lt;/span&gt; automatically names the module with an upper case first letter (&lt;code&gt;Example&lt;/code&gt;), but you use &lt;code&gt;require 'example'&lt;/code&gt; to include it, as we&amp;#8217;ll see shortly.&lt;/p&gt;


	&lt;h3&gt;Building&lt;/h3&gt;


	&lt;p&gt;See the &lt;code&gt;cpp/Makefile&lt;/code&gt; for the gory details. In a nutshell, you run the &lt;code&gt;swig&lt;/code&gt; command like this.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
        swig -c++ -ruby -Wall -o example_wrap.cpp example.i
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Next, you create a dynamically-linked library, as appropriate for your platform, so the Ruby interpreter can load the module dynamically when required. The &lt;code&gt;Makefile&lt;/code&gt; can do this for Linux and &lt;span class="caps"&gt;OS X&lt;/span&gt; platforms. See the &lt;a href="http://www.swig.org/Doc1.3/Ruby.html"&gt;Ruby section&lt;/a&gt; of the &lt;span class="caps"&gt;SWIG&lt;/span&gt; manual for Windows specifics.&lt;/p&gt;


	&lt;p&gt;If you test-drive your code, which tends to drive you towards minimally-coupled &amp;#8220;modules&amp;#8221;, then you can keep your libraries and build times small, which will make the build and test cycle very fast!&lt;/p&gt;


	&lt;h3&gt;&lt;code&gt;spec/cexample_spec.rb&lt;/code&gt; and &lt;code&gt;spec/cppexample_spec.rb&lt;/code&gt;&lt;/h3&gt;


	&lt;p&gt;Finally, here are the RSpec files that exercise the C and C&amp;#043;&amp;#043; code. (Disclaimer: these aren&amp;#8217;t the best spec files I&amp;#8217;ve ever written. For one thing, they don&amp;#8217;t exercise all the &lt;code&gt;CppExample&lt;/code&gt; methods! So sue me&amp;#8230; :)&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
        require File.dirname(__FILE__) + '/spec_helper'
        require 'example'

        describe "Example (C functions)" do
          it "should be a constant on Module" do
            Module.constants.should include('Example')
          end
          it "should have the methods defined in the C header file" do
            Example.methods.should include('returnString')
            Example.methods.should include('returnDouble')
            Example.methods.should include('doNothing')
          end
        end

        describe Example, ".returnString" do
          it "should return the input char * string as a Ruby string unchanged" do
            Example.returnString("bar!").should == "bar!" 
          end  
        end

        describe Example, ".returnDouble" do
          it "should return the input integer as a double" do
            Example.returnDouble(10).should == 10.0
          end
        end

        describe Example, ".doNothing" do
          it "should exist, but do nothing" do
            lambda { Example.doNothing }.should_not raise_error
          end
        end
    &lt;/code&gt;
&lt;/pre&gt;

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


&lt;pre&gt;
    &lt;code&gt;
    require File.dirname(__FILE__) + '/spec_helper'
    require 'example'

    describe Example::CppExample do
      it "should be a constant on module Example" do
        Example.constants.should include('CppExample')
      end
    end

    describe Example::CppExample, ".new" do
      it "should create a new object of type CppExample" do
        example = Example::CppExample.new("example1", 1)
        example.title.should == "example1" 
        example.flag.should  == 1
      end
    end

    describe Example::CppExample, "#title(value)" do
      it "should set the title" do
        example = Example::CppExample.new("example1", 1)
        example.title("title2")
        example.title.should == "title2" 
      end
    end

    describe Example::CppExample, "#flag(value)" do
      it "should set the flag" do
        example = Example::CppExample.new("example1", 1)
        example.flag(2)
        example.flag.should == 2
      end
    end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;If you love RSpec like I do, this is a very compelling thing to see!&lt;/p&gt;


	&lt;p&gt;And now for the small print:&lt;/p&gt;


	&lt;h2&gt;Current Limitations&lt;/h2&gt;


	&lt;p&gt;As I said, this is just an experiment at this point. Volunteers to make this &lt;em&gt;battle-ready&lt;/em&gt; would be most welcome!&lt;/p&gt;


	&lt;h3&gt;General&lt;/h3&gt;


	&lt;h4&gt;The Example &lt;code&gt;Makefile&lt;/code&gt; File&lt;/h4&gt;


	&lt;p&gt;&lt;strong&gt;It Must Be Hand Edited for Each New or Renamed Source File&lt;/strong&gt;&lt;/p&gt;


	&lt;p&gt;You&amp;#8217;ve probably already solved this problem for your own make files. Just merge in the example &lt;code&gt;Makefile&lt;/code&gt; to pick up the &lt;span class="caps"&gt;SWIG&lt;/span&gt;- and RSpec-related targets and rules.&lt;/p&gt;


	&lt;p&gt;&lt;strong&gt;It Only Knows How to Build Shared Libraries for Mac &lt;span class="caps"&gt;OS X&lt;/span&gt; and Linux (and Not Very Well)&lt;/strong&gt;&lt;/p&gt;


	&lt;p&gt;Some definitions are probably unique to my &lt;span class="caps"&gt;OS X&lt;/span&gt; and Linux machines. Windows is not supported at all. However, this is also easy rectify. Start with the notes in the &lt;code&gt;Makefile&lt;/code&gt; itself.&lt;/p&gt;


	&lt;h4&gt;The &lt;code&gt;module.i&lt;/code&gt; File Must Be Hand Edited for Each File Change&lt;/h4&gt;


	&lt;p&gt;Since the format is simple, a make task could fill a template file with the changed list of source files during the build.&lt;/p&gt;


	&lt;h4&gt;Better Automation&lt;/h4&gt;


	&lt;p&gt;It should be straightforward to provide scripts, &lt;span class="caps"&gt;IDE&lt;/span&gt;/Editor shortcuts, &lt;em&gt;etc&lt;/em&gt;. that automate some of the tasks of adding new methods and classes to your C and C&amp;#043;&amp;#043; code when you introduce them  &lt;i&gt;first&lt;/i&gt; in your &amp;#8220;spec&amp;#8221; files. (The true &lt;span class="caps"&gt;TDD&lt;/span&gt; way, of course.)&lt;/p&gt;


	&lt;h3&gt;Specific Issues for C Code Testing&lt;/h3&gt;


	&lt;p&gt;I don&amp;#8217;t know of any other C-specific issues, so unit testing with Ruby is most viable today for C code. Although I haven&amp;#8217;t experimented extensively, C functions and variables are easily mapped by &lt;span class="caps"&gt;SWIG&lt;/span&gt; to a Ruby module. The &lt;a href="http://www.swig.org/Doc1.3/Ruby.html"&gt;Ruby section&lt;/a&gt; of the &lt;span class="caps"&gt;SWIG&lt;/span&gt; manual discusses this mapping in some detail.&lt;/p&gt;


	&lt;h3&gt;Specific Issues for C&amp;#043;&amp;#043; Code Testing&lt;/h3&gt;


	&lt;p&gt;More work will be required to make this viable. It&amp;#8217;s important to note that &lt;span class="caps"&gt;SWIG&lt;/span&gt; cannot handle all C&amp;#043;&amp;#043; constructs (although there are workarounds for most issues, if you&amp;#8217;re committed to this approach&amp;#8230;). For example, namespaces, nested classes, some template and some method overloading scenarios are not supported. The &lt;a href="http://www.swig.org/Doc1.3"&gt;&lt;span class="caps"&gt;SWIG&lt;/span&gt; manual&lt;/a&gt; has details.&lt;/p&gt;


	&lt;p&gt;Also, during my experiment, &lt;span class="caps"&gt;SWIG&lt;/span&gt; didn&amp;#8217;t seem to map &lt;code&gt;const std::string&amp;#38;&lt;/code&gt; objects in C&amp;#043;&amp;#043; method signatures to Ruby strings, as I would have expected (&lt;code&gt;char*&lt;/code&gt; worked fine).&lt;/p&gt;


	&lt;h2&gt;Is It a Viable Approach?&lt;/h2&gt;


	&lt;p&gt;Once the &lt;strong&gt;General&lt;/strong&gt; issues listed above are handled, I think this approach would work very well for C code. For C&amp;#043;&amp;#043; code, there are more issues that need to be addressed, and programmers who are committed to this strategy will need to tolerate some issues (or just use C&amp;#043;&amp;#043;-language tools for some scenarios).&lt;/p&gt;


	&lt;h2&gt;Conclusions: Making It Development-Team Ready&lt;/h2&gt;


	&lt;p&gt;I&amp;#8217;d like to see this approach pushed to its logical limit. I think it has the potential to really improve the productivity of C and C&amp;#043;&amp;#043; developers and the quality of their test coverage, by leveraging the productivity and power of dynamically-typed languages like Ruby. If you prefer, you could use Tcl, Python, even Java instead.&lt;/p&gt;


	&lt;h3&gt;License&lt;/h3&gt;


	&lt;p&gt;This code is complete open and free to use. Of course, use it at your own risk; I offer it without warranty, &lt;em&gt;etc.&lt;/em&gt;, &lt;em&gt;etc&lt;/em&gt;. When I polish it to the point of making it an &amp;#8220;official&amp;#8221; project, I will probably release under the Apache license.&lt;/p&gt;


	&lt;p id="fn1"&gt;&lt;sup&gt;1&lt;/sup&gt; I spent a lot of time debugging problems because I had a &amp;#8217;#&amp;#8217; where I should have had a &amp;#8217;%&amp;#8217;! &lt;em&gt;Caveat emptor&lt;/em&gt;!&lt;/p&gt;</description>
      <pubDate>Mon, 04 Feb 2008 22:08:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:cba4dc23-cbce-4173-be6f-14c7847dcfea</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/02/04/unit-testing-c-and-c-with-ruby-and-rspec</link>
      <category>Embedded</category>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>Agile Methods</category>
      <category>c</category>
      <category>RSpec</category>
      <category>Ruby</category>
      <category>TDD</category>
      <category>testing</category>
    </item>
    <item>
      <title>ANN: Talks at the Chicago Ruby Users Group (Oct. 1, Dec. 3)</title>
      <description>&lt;p&gt;I&amp;#8217;m speaking on &lt;a href="http://aquarium.rubyforge.org"&gt;Aquarium&lt;/a&gt; this Monday night (Oct. 1st). Details are &lt;a href="http://chirb.org"&gt;here&lt;/a&gt;. David Chelimsky will also be talking about new developments in RSpec and RBehave.&lt;/p&gt;


	&lt;p&gt;At the Dec. 3 Chirb meeting, the two of us are reprising our Agile 2007 tutorial &lt;em&gt;Ruby&amp;#8217;s Secret Sauce: Metaprogramming&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Please join us!&lt;/p&gt;</description>
      <pubDate>Sat, 29 Sep 2007 09:52:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:430c0979-4e0c-4a0c-8afd-57b3579618d1</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2007/09/29/ann-talks-at-the-chicago-ruby-users-group-oct-1-dec-3</link>
      <category>Dean's Deprecations</category>
      <category>Public Speaking Engagements</category>
      <category>Dynamic Languages</category>
      <category>Ruby</category>
      <category>aquarium</category>
      <category>Metaprogramming</category>
      <category>AOP</category>
      <category>aspects</category>
      <category>Chirb</category>
    </item>
    <item>
      <title>Strongly Typed Languages Considered Dangerous</title>
      <description>&lt;p&gt;Have you ever heard of covariance? Method parameters or returns are said to be covariant if, as you work your way down an inheritance hierarchy, the types of the formal parameters or return type in an overridden method can be sub-types of the formal parameters and return types in the superclass&amp;#8217; version of the  method.&lt;/p&gt;


	&lt;p&gt;Oh, and contravariance is just the opposite.&lt;/p&gt;


	&lt;p&gt;What?! Why should you care? Answer, you shouldn&amp;#8217;t. Yes C++ and Java both support covariant return types, but so what? Have you ever used them? OK, I have, but then I also used and liked C++ for about 7 years, over 10 years ago. We all learn to move on.&lt;/p&gt;


	&lt;p&gt;You ever notice how something meant to help often (typically?) turns out to do exactly the opposite? Even worse, it directly supports or enables another unfortunate behavior. This is just Weinberg&amp;#8217;s first rule of problem solving:&lt;/p&gt;


&lt;h1&gt;Every solution introduces new problems&lt;/h1&gt;
&lt;P&gt;
&lt;P&gt;

	&lt;p&gt;Here&amp;#8217;s an example I&amp;#8217;m guilty of. Several years ago I was working on a project where we had written many unit tests. We had not followed the &lt;span class="caps"&gt;FIRST&lt;/span&gt; principles, specifically R-Reliability. Our tests were hugely affected by the environment. We had copies of real databases that would get overridden without warning. We&amp;#8217;d have problems with MQ timeouts at certain times of the day or sometimes for days. And our tests would fail.&lt;/p&gt;


	&lt;p&gt;We wold generally have &amp;#8220;events&amp;#8221; that would cause tests to fail for some time. We were using continuous integration and so to &amp;#8220;fix&amp;#8221; the problem, I created a class we called &amp;#8220;TimeBomb&amp;#8221; &amp;#8211; turns out it was the right name for the wrong reason.&lt;/p&gt;


	&lt;p&gt;You&amp;#8217;d put a TimeBomb in a test and then comment out the test. The TimeBomb would be given a date. Until that date, the test would &amp;#8220;pass&amp;#8221; &amp;#8211; or rater be ignored. At some point in the future, the TimeBomb would expire and tests would start failing again.&lt;/p&gt;


	&lt;p&gt;I was so proud of it, I even took the time to write something up about it &lt;a href="http://schuchert.wikispaces.com/JUnit+4.xTimeBombGenericCodeExplained"&gt;here&lt;/a&gt;.
I had nothing but the best intentions. I wanted an active mechanism to remind us of work that needed to be done. We had so many todo&amp;#8217;s and warnings that anything short of an active reminder would simply be missed. I also wanted CI to &amp;#8220;work.&amp;#8221; But what eventually happened was that as our tests kept failing, we&amp;#8217;d simply keep moving the TimeBomb date out.&lt;/p&gt;


	&lt;p&gt;I wrote something that enabled our project to collect more design debt. As I said, my intentions were noble. But the road to Hell is paved with good intentions. Luckily I got the name right. The thing that was really blowing up, however, was the project itself.&lt;/p&gt;


	&lt;p&gt;What has all of this got to do with &amp;#8220;strongly typed languages&amp;#8221;?&lt;/p&gt;


	&lt;p&gt;If you&amp;#8217;re working with a strongly typed language, you will have discussions about covariance (well I do anyway). You&amp;#8217;ll discuss the merits of multiple inheritance (it really is a necessary feature &amp;#8211; let the flames rise, I&amp;#8217;m already in Hell from my good intentions). You&amp;#8217;ll also discuss templates/generics. The list goes on and on.&lt;/p&gt;


	&lt;p&gt;If you&amp;#8217;re working with a dynamically typed language (the first one I used professionally was Smalltalk but I also used Self, Objective-C, which lets you choose, and several other languages whose names I do not recall).&lt;/p&gt;


	&lt;p&gt;Covariance is not even an issue. The same can be said of generics/templates and yes, even multiple inheritance is less of an issue. In a strongly-typed languages, things like Multiple Inheritance&lt;b&gt;&lt;i&gt; are necessary&lt;/i&gt;&lt;/b&gt; if you want your type system to be complete. (If you don&amp;#8217;t believe me, read a copy of Object Oriented Software Construction, 2nd ed. by Bertrand Meyer &amp;#8211; an excellent read.)&lt;/p&gt;


	&lt;p&gt;Ever created a mock object in a typed language? You either need an interface or at least a non-final class. What about Ruby or Smalltalk? Nope. Neither language cares about a class&amp;#8217; interface until it executes. And neither language cares how a class is able respond to a particular message, just that it does. It&amp;#8217;s even possible in both languages to &lt;span class="caps"&gt;NOT&lt;/span&gt; have a method and still work if you mess with the meta-language protocol.&lt;/p&gt;


	&lt;p&gt;OK, but still, does this make typed languages bad?&lt;/p&gt;


	&lt;p&gt;Lets go back to that issue of enabling bad things.&lt;/p&gt;


	&lt;p&gt;Virtual Machines, like the &lt;span class="caps"&gt;JVM&lt;/span&gt; and &lt;span class="caps"&gt;CLR&lt;/span&gt;, have made amazing strides in the past few years. Reflection keeps getting faster. Just in time compilers keep getting smarter. The time required for intrinsic locks has improved and now a Java 5 compiler will support non-blocking, safe, multi-threaded updates. Modern processors support such operations using an optimistic approach. Heck, Java 6 even does some cool stuff with local object references to significantly improve Java&amp;#8217;s memory usage. Java runs pretty fast.&lt;/p&gt;


	&lt;p&gt;Dynamic languages, generally, are not there yet. I hope they get there, but they simply are not there. But so what?! If your system runs &amp;#8220;fast enough&amp;#8221; then it&amp;#8217;s fast enough. People used Smalltalk for real applications years ago &amp;#8211; and still do to some extent. Ruby is certainly fast enough for a large class of problems.&lt;/p&gt;


	&lt;p&gt;How is that? These languages force you to write well. If you do not, then you will write code that is not &amp;#8220;fast enough.&amp;#8221; I&amp;#8217;ve see very poor performing Smalltalk solutions. But it was never because of Smalltalk, it was because of poor programming practices. Are there things that won&amp;#8217;t currently perform fast enough in dynamically typed languages? Yes. Are most applications like that? Probably not.&lt;/p&gt;


	&lt;p&gt;You can&amp;#8217;t get away with as much in a dynamically typed language. That sounds ironic. On the one hand you have amazing power with dynamically typed languages. Of course Peter Parker learned that &amp;#8220;With great power comes great responsibility.&amp;#8221; This is just as true with Ruby and other dynamically typed languages.&lt;/p&gt;


	&lt;p&gt;You do not have as much to guide you in a dynamically typed language. Badly written, poorly organized code in a typed language is hard to follow but it&amp;#8217;s possible. In a language like Ruby or Smalltalk it&amp;#8217;s still possible but it&amp;#8217;s a lot harder. Such poor approaches will typically fail sooner. And thats &lt;span class="caps"&gt;GOOD&lt;/span&gt;! You&amp;#8217;ve wasted less money because you failed sooner. If you&amp;#8217;ve got crappy design, you&amp;#8217;re going to fail. The issue is how much time/money will you spend to get there.&lt;/p&gt;


	&lt;p&gt;Another thing that strongly typed languages offer is a false sense of security because of compiler errors. I have heard many people deride the need for unit tests because the compiler &amp;#8220;will catch it.&amp;#8221;&lt;/p&gt;


	&lt;p&gt;This misses a significant point that unit tests can serve as a&lt;b&gt;&lt;i&gt;  specification&lt;/b&gt;&lt;/i&gt; of behavior rather than just a validation of as-written code.&lt;/p&gt;


	&lt;p&gt;You cannot get away with as much in a dynamically typed language. Or put another way, a dynamically typed language does not enable you to be as sloppy. It&amp;#8217;s just a fact. In fact you can typically get away with a lot in a dynamically typed language, you just have to do it well.&lt;/p&gt;


	&lt;p&gt;Does this mean that dynamically typed languages are harder to work in? Maybe. But if you follow &lt;span class="caps"&gt;TDD&lt;/span&gt;, then the language is less important.&lt;/p&gt;


	&lt;p&gt;Do we need fast, typed languages? Clearly we do. There are applications where having such languages is necessary. Device drivers are not written in Ruby (maybe they are, I&amp;#8217;m just trying to be more balanced).&lt;/p&gt;


	&lt;p&gt;However, how many of you were around when games were written in assembly? C was not fast enough. Then C was fast enough but C++ was still a question mark. C++ and C became mainstream but Java was just too slow. Some games are getting written in Java now. Not many, but it&amp;#8217;s certainly possible. It is also possible to use multiple languages and put the time-critical stuff, which is generally a small part of your system, in one language and use another language for the rest of the system.&lt;/p&gt;


	&lt;p&gt;Back in the very early 90&amp;#8217;s I worked just a little bit with Self. At that time, their Just In Time compiler would create machine code from byte code for methods that got executed. They went one step further, however. Not only did they &lt;span class="caps"&gt;JIT&lt;/span&gt; compile a method for an object, they would actually do it for combinations of receivers and type parameters.&lt;/p&gt;


	&lt;p&gt;There&amp;#8217;s a name for this. In general it is called multi-dispatch (some languages support double-dispatch, the visitor pattern is a mechanism to turn standard polymorphism into a weak form of double dispatch, Smalltalk used a similar approach for handling numerical calculations).&lt;/p&gt;


	&lt;p&gt;Self was doing this not to support multi-dispatch but to improve performance. That means that a given method could have multiple compiled forms to handle commonly used methods on a receiver with commonly-used parameters. Yes it used more memory. But given what modern compilers do with code optimization, it just seems that this kind of technique could have huge benefits in the performance of dynamically typed languages. This is just one way a dynamic language can speed things up. There are others and they are happening &lt;span class="caps"&gt;NOW&lt;/span&gt;.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;m hoping that in the next few years dynamic languages will get more credit for what they have to offer. I believe they are the future. I still primarily develop in Java but that&amp;#8217;s just because I&amp;#8217;m waiting for the dust to settle a little bit and for a clear dynamic language to start to assert itself. I like Ruby (though its support for block closures is, &lt;span class="caps"&gt;IMO&lt;/span&gt;, weak). I&amp;#8217;m not convinced Ruby is the next big thing. I&amp;#8217;m working with it a little bit just in case, however.&lt;/p&gt;


	&lt;p&gt;What are you currently doing that enables yourself or your co-workers to maintain the status quo?&lt;/p&gt;</description>
      <pubDate>Thu, 23 Aug 2007 18:37:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:3775098f-f80a-440c-8f92-833f99de5296</guid>
      <author>Brett Schuchert</author>
      <link>http://blog.objectmentor.com/articles/2007/08/23/strongly-typed-languages-considered-dangerous</link>
      <category>Schuchert's Scattered Synapses </category>
      <category>dynamic</category>
      <category>languages</category>
      <category>Ruby</category>
      <category>strong</category>
      <category>typing</category>
    </item>
    <item>
      <title>Announcement: Aquarium v0.1.0 - An Aspect-Oriented Programming Toolkit for Ruby</title>
      <description>I just released the first version of a new Aspect-Oriented Programming toolkit for Ruby called &lt;a href="http://aquarium.rubyforge.org/"&gt;Aquarium&lt;/a&gt;. 

I blogged about the goals of the project &lt;a href="http://blog.aspectprogramming.com/"&gt;here&lt;/a&gt;. Briefly, they are 
&lt;ul&gt;
&lt;li&gt;Create a powerful &lt;i&gt;pointcut language&lt;/i&gt;, the most important part of an AOP toolkit.
&lt;li&gt;Provide Robust support for concurrent &lt;i&gt;advice&lt;/i&gt; at the same &lt;i&gt;join point.&lt;/i&gt;.
&lt;li&gt;Provide runtime addition and removal of aspects.&lt;/li&gt;
&lt;li&gt;Provide a test bed for implementation ideas for &lt;a href="http://www.martinfowler.com/bliki/DomainSpecificLanguage.html"&gt;DSL's&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;

There is extensive documentation at the &lt;a href="http://aquarium.rubyforge.org/"&gt;Aquarium&lt;/a&gt; site. Please give it a try and let me know what you think!


</description>
      <pubDate>Thu, 23 Aug 2007 17:26:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:ef446f2a-179b-4d3e-8a33-f7ef1d49a9dc</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2007/08/23/announcement-aquarium-v0-1-0-an-aspect-oriented-programming-toolkit-for-ruby</link>
      <category>Dean's Deprecations</category>
      <category>Dynamic Languages</category>
      <category>aspect</category>
      <category>oriented</category>
      <category>programming</category>
      <category>Ruby</category>
      <category>aquarium</category>
      <trackback:ping>http://blog.objectmentor.com/articles/trackback/8799</trackback:ping>
    </item>
    <item>
      <title>Applications Should Use Several Languages</title>
      <description>&lt;p&gt;Yesterday, I &lt;a href="http://typo.objectmentor.com/articles/2007/07/03/observations-on-tdd-in-c-long"&gt;blogged&lt;/a&gt; about &lt;a href="http://typo.objectmentor.com/articles/2007/07/03/observations-on-tdd-in-c-long"&gt;&lt;span class="caps"&gt;TDD&lt;/span&gt; in C++&lt;/a&gt; and ended with a suggestion for the dilemma of needing optimal performance some of the time and optimal productivity the rest of the time. I suggested that you should use more than one language for your applications.&lt;/p&gt;


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


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


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


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


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


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


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


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


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

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