<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>spiros.blog()</title>
	<atom:link href="http://www.tzavellas.com/techblog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.tzavellas.com/techblog</link>
	<description>Spiros Tzavellas’s blog, mostly on software development and Java.</description>
	<lastBuildDate>Fri, 24 Sep 2010 07:42:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>A Scala implementation of Circuit Breaker</title>
		<link>http://www.tzavellas.com/techblog/2010/09/21/scala-implementation-circuit-breaker/</link>
		<comments>http://www.tzavellas.com/techblog/2010/09/21/scala-implementation-circuit-breaker/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 00:32:59 +0000</pubDate>
		<dc:creator>spiros</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[circuit-breaker]]></category>
		<category><![CDATA[stability]]></category>

		<guid isPermaLink="false">http://www.tzavellas.com/techblog/?p=286</guid>
		<description><![CDATA[In this post I&#8217;ll describe how to use sse-breaker, a small library that implements the Circuit Breaker stability design pattern in Scala. Before mentioning any sse-breaker specifics lets quickly define what is a Circuit Breaker. A Circuit Breaker is a software component that keeps track of the error rate of various operations and when the [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I&#8217;ll describe how to use <a href="http://github.com/sptz45/sse-breaker">sse-breaker</a>, a small library that implements the Circuit Breaker stability design pattern in <a href="http://www.scala-lang.org">Scala</a>.</p>
<p>Before mentioning any  <a href="http://github.com/sptz45/sse-breaker">sse-breaker</a> specifics lets quickly define what is a Circuit Breaker. A Circuit Breaker is a software component that keeps track of the error rate of various operations and when the rate is high it prevents those operation from executing by <em>failing-fast</em>.</p>
<p>In <a href="http://github.com/sptz45/sse-breaker">sse-breaker</a> the Circuit Breaker is implemented as an executor. To use it you create a <code>CircuitExecutor</code> instance and call its <code>apply[T](op: =>T):T</code> method passing the code that you would like to execute in the closure. Depending on the Circuit Breaker&#8217;s state (if errors have occurred recently) the executor will execute the requested operation or it will throw an <code>OpenCircuitException</code>.</p>
<p>For example lets say that we are developing a web application that uses the <a href="http://dev.twitter.com/start">Twitter API</a>. Obviously we wouldn&#8217;t want any capacity problems at <a href="http://twitter.com">Twitter</a> (or any other site) to prevent our pages from rendering fast. To protect our application we could wrap any calls to the <a href="http://dev.twitter.com/start">Twitter API</a> with a Circuit Breaker.</p>
<p>To do this in <a href="http://github.com/sptz45/sse-breaker">sse-breaker</a> we could use the following code:</p>
<pre lang="scala">
class TwitterGateway(twitter: Twitter) {

  private val failfast = new CircuitExecutor("twitter-breaker")

  def getTimeline: List[Status] = failfast {
    twitter.getFriendsTimeline
  }

  def search(q: Query): QueryResult = failfast {
    twitter.search(q)
  }
}
</pre>
<p>In the above code we&#8217;ve created a <code>CircuitExecutor</code>, named <em>twitter-breaker</em>, with the default configuration and wrapped the calls to the Twitter API. By default if five exceptions are thrown within a minute the Circuit Breaker will go into the <em>open</em> state and further requests to execute any operation, for the next 10 minutes, will throw an <code>OpenCircuitException</code> instead of executing the operation.</p>
<p>For more information see the homepage of <a href="http://www.github.com/sptz45/sse-breaker">sse-breaker</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tzavellas.com/techblog/2010/09/21/scala-implementation-circuit-breaker/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Catching Throwable in Scala</title>
		<link>http://www.tzavellas.com/techblog/2010/09/20/catching-throwable-in-scala/</link>
		<comments>http://www.tzavellas.com/techblog/2010/09/20/catching-throwable-in-scala/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 06:38:21 +0000</pubDate>
		<dc:creator>spiros</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[exceptions]]></category>

		<guid isPermaLink="false">http://www.tzavellas.com/techblog/?p=427</guid>
		<description><![CDATA[Because of Scala&#8216;s pattern matching syntax it is really convenient to catch Throwable instead of Exception or any other exception type. Instead of writing: try { iMayHaveIllegalState.doSomething() } catch { case e: IllegalStateException => e.printStackTrace() } we can simply write: try { iMayHaveIllegalState.doSomething() } catch { case e => e.printStackTrace() } You might be tempted [...]]]></description>
			<content:encoded><![CDATA[<p>Because of <a href="http://www.scala-lang.org">Scala</a>&#8216;s <a href="http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-4">pattern matching</a> syntax it is really convenient to catch <code>Throwable</code> instead of <code>Exception</code> or any other exception type. Instead of writing:</p>
<pre>
try {
  iMayHaveIllegalState.doSomething()
} catch {
  case e: IllegalStateException => e.printStackTrace()
}
</pre>
<p>we can simply write:</p>
<pre>
try {
  iMayHaveIllegalState.doSomething()
} catch {
  case e => e.printStackTrace()
}
</pre>
<p>You might be tempted to use the above code in your programs since it is shorter but if catching <code>Throwable</code> in Java is <a href="http://www.javatuning.com/why-catch-throwable-is-evil-real-life-story/">evil</a> then <strong>catching <code>Throwable</code> in Scala is ten times more evil</strong>.</p>
<p>To illustrate this we will use a small example. Lets say that we want to write a method that takes a sequence of strings and tries to find if it contains a string that represents an even number. Furthermore if any of the strings cannot get converted into an integer then we assume that the input is invalid and return <code>false</code>.</p>
<p>A possible implementation is the following:</p>
<pre>
def containsEven(nums: String*): Boolean = {
  try {
    for (i <- nums) {
      if (i.toInt % 2 == 0)
        return true
    }
  } catch { case e => () }
  false
}
</pre>
<p>From the above implementation we would expect that <code>containsEven("1", "3")</code> should return <code>false</code> and that <code>containsEven("2", "3")</code> should return <code>true</code>. Unfortunately this is not the case and regardless of the input our method always returns <code>false</code>. This is because in the <code>catch</code> block we used a pattern that catches <code>Throwable</code> with the expression <code>case e => ...</code> instead of the longer but more correct pattern <code>case e: NumberFormatException => ...</code> that only catches <code>NumberFormatException</code>. To understand why this is the cause of the bug we need to understand how Scala implements <em>non-local return</em> from closures.</p>
<p>The <code>for</code> loop in the above code is actually a method call to the the <code>foreach</code> method of the <code>nums</code> object (that is an instance of <code>scala.Seq</code>) passing the body of the <code>for</code> loop as a closure in the <code>foreach</code> method. The code inside the <code>for</code> loop is actually the <code>apply(..)</code> method of the closure (a <code>scala.Function1</code> in our case). Since that code belongs in another method normally a <code>return</code> statement present in that code would signal the return of that method.</p>
<p>This is not the case for Scala&#8217;s closures and when a <code>return</code> statement is present in a closure, the closure instead of returning at the point of invocation it also triggers the return of the enclosing method. This behavior is called <em>non-local return</em> and it is essential for creating control-flow abstractions using closures.</p>
<p>Because the JVM does not have native support for <em>non-local return</em> Scala implements it by throwing a <code>Throwable</code>. When a closure contains a <code>return</code> statement then that closure when executed instead of returning normally it throws a <code>Throwable</code> of type  <a href="http://www.scala-lang.org/api/current/scala/runtime/NonLocalReturnControl.html"><code>scala.runtime.NonLocalReturnControl</code></a> that contains the returned value of the closure. The <code>NonLocalReturnControl</code> is then caught at the enclosing method and closure&#8217;s returned value is returned from the enclosing method. This is why when we try to define a closure that contains a <code>return</code> statement outside of a method the compiler will complain with an error because it cannot find where to generate the catch block for the <code>NonLocalReturnControl</code> thrown from the closure.</p>
<p>With the knowledge of how <em>non-local return</em> is implemented in Scala, we can now see that in the <code>containsEven</code> method the <code>NonLocalReturnControl</code> that gets thrown from the <code>return true</code> statement in the <code>for</code> loop gets caught by our <code>case e => ()</code> pattern and gets ignored. So regardless of the input <code>containsEven</code> will always return <code>false</code>. To fix this we must simply catch <code>NumberFormatException</code> and not <code>Throwable</code>.</p>
<pre>
def containsEven(nums: String*): Boolean = {
  try {
    for (i <- nums) {
      if (i.toInt % 2 == 0)
        return true
    }
  } catch { case e: NumberFormatException => () }
  false
}
</pre>
<p>Catching <code>Throwable</code> can be a source of frequent bugs because even with the knowledge of how <em>non-local return</em> is implemented it is very likely that you will miss a closure with <em>non-local return</em> and introduce a bug. Furthermore Scala implements and other control structures by throwing <code>Throwable</code> like <a href="http://www.scala-lang.org/api/current/scala/util/control/Breaks.html">break</a> and <a href="http://www.scala-lang.org/api/current/scala/util/continuations/package.html">continuations</a> making it even harder.</p>
<p>In the rare case when you absolutely need to catch <code>Throwable</code> the correct way to do it is the following:</p>
<pre>
import scala.util.control.ControlThrowable

try {
  codeThatMayThrowThrowable()
} catch {
  case e: ControlThrowable => throw e
  case e => handleThrowable(e)
}
</pre>
<p>In the above code we re-throw a <code>Throwable</code> if it is used for control-flow and handle all others. The <a href="http://www.scala-lang.org/api/current/scala/util/control/ControlThrowable.html"><code>scala.util.control.ControlThrowable</code></a> is the <code>Throwable</code> that is extended by all throwables that are used for control flow in Scala.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tzavellas.com/techblog/2010/09/20/catching-throwable-in-scala/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t use vars inside singleton objects</title>
		<link>http://www.tzavellas.com/techblog/2010/09/20/var-singleton-objects/</link>
		<comments>http://www.tzavellas.com/techblog/2010/09/20/var-singleton-objects/#comments</comments>
		<pubDate>Mon, 20 Sep 2010 06:36:16 +0000</pubDate>
		<dc:creator>spiros</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[antipattern]]></category>

		<guid isPermaLink="false">http://www.tzavellas.com/techblog/?p=344</guid>
		<description><![CDATA[Scala enables immutability and functional programming but it does not dictate it. As easy it is to create immutable state via a val it is equally easy to create mutable state via a var. IMHO this is a good thing since the programmer is free to choose the programming style to use according to the [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.scala-lang.org">Scala</a> enables immutability and functional programming but it does not dictate it. As easy it is to create immutable state via a <code>val</code> it is equally easy to create mutable state via a <code>var</code>. IMHO this is a good thing since the programmer is free to choose the programming style to use according to the problem at hand.</p>
<p>One of Scala&#8217;s unique features is <a href="http://www.naildrivin5.com/scalatour/wiki_pages/ScalaObject">singleton objects</a>. Singleton objects are an implementation of the <a href="http://en.wikipedia.org/wiki/Singleton_pattern">Singleton</a> design pattern inside the language and they allow Scala to abandon static methods and provide a more uniform view of the world where <a href="http://www.scala-lang.org/node/128">everything is an object</a>.</p>
<p>Singleton objects despite all their benefits they make one bad practice very convenient to do. It is very easy to forget that an <code>object</code> (that is not defined inside a <code>class</code> or <code>trait</code>) is actually a global static and thus a <code>var</code> inside that <code>object</code> is actually <em>global mutable state</em>.</p>
<p>This is not a Scala weakness and I believe it is more a weakness of the programmer to come up with the right design given his unfamiliarity with the Scala constructs. When we start using a new programming language because we are re-evaluating our view of programming certain bad practices that we might never used in our previous language temporarily become more tempting. </p>
<p>One example of global mutable state in a top-level singleton object that I saw recently is in <a href="http://www.squeryl.org">Squeryl</a>. Squeryl is an ORM that has a really slick API and IMHO could become a viable alternative to the major Java ORMs for Scala.</p>
<p>I was reading Squeryl&#8217;s documentation and I got really excited about using it in a small project but then I saw the <a href="http://github.com/max-l/Squeryl/blob/2b55037ed79a3c4531e5b7ec50a29a1f3a1c03c8/src/main/scala/org/squeryl/Session.scala">SessionFactory</a> object and my excitement turned into disappointment. Below I have a small fragment from the <code>SessionFactory</code>&#8216;s code:</p>
<pre lang="scala">
object SessionFactory {

  var concreteFactory: Option[()=>Session] = None

  var externalTransactionManagementAdapter: Option[()=>Session] = None

  def newSession: Session = {
    /* Code that uses concreteFactory... */
  }
}
</pre>
<p>As you can see from the above code the <code>SessionFactory</code> has two <code>var</code>s that hold functions that create <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">ORM sessions</a>. I have to say that I am at least uncomfortable with an ORM that relies on <em>global mutable state</em> for that functionality.</p>
<p>Lets try to enumerate some of the disadvantages of Squeryl&#8217;s current design:</p>
<ol>
<li>Since the <code>concreteFactory</code> and <code>externalTransactionManagementAdapter</code> can be changed from anywhere in the program it is difficult to reason about our code.</li>
<li>The API of <code>SessionFactory</code> is not <em>thread-safe</em>. For example if a thread changes <code>concreteFactory</code> then another thread reading that variable does not have a guarantee that will see the latest version.</li>
<li>Since the configuration for creating a <code>Session</code> is in a static variable this means that we cannot have a multi-threaded application that uses two different configurations.</li>
<li>As a consequence of the above we cannot deploy Squeryl as an OSGi bundle and use it from multiple applications.</li>
<li>Since we depend on global state, our code is more difficult to test because we need to reset that state after every test.</li>
<li>Furthermore we cannot run our tests in parallel.</li>
</ol>
<p>Lots of bad stuff for two innocent <code>var</code>s&#8230;</p>
<p><strong>Update:</strong> Maxime Lévesque, the author of Squeryl, wrote in a comment that Squeryl also provides a mechanism for working with sessions that does not rely on static state and that the mechanism described in this article is optional and provided for convenience. So my analysis above is not true and would only be valid if Squeryl didn&#8217;t provide an alternative mechanism.</p>
<p>In conclusion:</p>
<ul>
<li>Putting a <code>var</code> inside an <code>object</code> might be convenient but as each instance of <em>global mutable state</em> it can lead to a lot of trouble.</li>
<li>Just because you moved to a new programming language doesn&#8217;t mean that your old practices are now unnecessary.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.tzavellas.com/techblog/2010/09/20/var-singleton-objects/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Making Guice more Scala friendly</title>
		<link>http://www.tzavellas.com/techblog/2010/08/22/making-guice-more-scala-friendly/</link>
		<comments>http://www.tzavellas.com/techblog/2010/08/22/making-guice-more-scala-friendly/#comments</comments>
		<pubDate>Sun, 22 Aug 2010 20:25:28 +0000</pubDate>
		<dc:creator>spiros</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[guice]]></category>

		<guid isPermaLink="false">http://www.tzavellas.com/techblog/?p=265</guid>
		<description><![CDATA[Guice might be one of the few libraries that is easier to use in Java than it is in Scala. The main reason for this is the absence of class literals in Scala. Instead of writing Service.class in Scala we write classOf[Service] which is longer and less readable. To illustrate this lets compare two Guice [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/p/google-guice/">Guice</a> might be one of the few libraries that is easier to use in <a href="http://www.oracle.com/technetwork/java/index.html">Java</a> than it is in <a href="http://www.scala-lang.org">Scala</a>. The main reason for this is the absence of class literals in Scala. Instead of writing <code>Service.class</code> in Scala we write <code>classOf[Service]</code> which is longer and less readable. To illustrate this lets compare two Guice modules, one defined in Java and the other in Scala.</p>
<p>Below we have a small Guice module (copied from the documentation of <a href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/AbstractModule.html"><code>AbstractModule</code></a>) defined in Java.</p>
<pre lang="java">
public class MyModule extends AbstractModule {
  protected void configure() {
    bind(Service.class).to(ServiceImpl.class).in(Singleton.class);
    bind(CreditCardPaymentService.class);
    bind(PaymentService.class).to(CreditCardPaymentService.class);
    bindConstant().annotatedWith(Names.named("port")).to(8080);
  }
}
</pre>
<p>In Scala the above code would be:</p>
<pre lang="scala">
class MyModule extends AbstractModule {
   protected def configure() {
     bind(classOf[Service]).to(classOf[ServiceImpl]).in(classOf[Singleton])
     bind(classOf[CreditCardPaymentService])
     bind(classOf[PaymentService]).to(classOf[CreditCardPaymentService])
     bindConstant().annotatedWith(Names.named("port")).to(8080)
   }
 }
</pre>
<p>As you can see the code is longer and it looses the DSL feel that it has in the Java version. This fact may lead Scala developers away from Guice since defining Guice modules in Scala feels awkward and leaves a lot to be desired.</p>
<p>For this reason I&#8217;ve created a small project, called <a href="http://github.com/sptz45/sse-guice">sse-guice</a>, that extends Guice&#8217;s internal DSL with methods that make defining Guice modules in Scala more pleasant.</p>
<p>What I&#8217;ve done is to extend the binder interfaces of Guice (defined in <a href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/binder/package-summary.html"><code>com.google.inject.binder</code></a> package) and add a method that takes a <code>Manifest</code> for each method that takes a <code>Class</code> as a parameter. Furthermore I&#8217;ve extended the <a href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/AbstractModule.html"><code>AbstractModule</code></a> class (the entry point of the Guice internal DSL) and added a bind method that accepts a <code>Manifest</code> and I&#8217;ve also overridden all the methods that return a binder interface to return the extended binder interfaces provided by <a href="http://github.com/sptz45/sse-guice">sse-guice</a>.</p>
<p>By utilizing <a href="http://github.com/sptz45/sse-guice">sse-guice</a> the above module can be rewritten as:</p>
<pre lang="scala">
class MyModule extends ScalaModule {
  protected def configure() {
    bind[Service].to[ServiceImpl].in[Singleton]
    bind[CreditCardPaymentService]
    bind[PaymentService].to[CreditCardPaymentService]
    bindConstant().annotatedWithName("port").to(8080)
  }
}
</pre>
<p>As you can see the code now is shorter, easier to read and feels like a proper internal DSL.</p>
<p>Another benefit of using <code>Manifest</code> as a parameter is that we can now avoid creating <code>TypeLiteral</code>s when we bind generic types. To bind a generic type in Guice you have to write:</p>
<pre lang="scala">
bind(new TypeLiteral[Validator[Registration]] {}).to(classOf[RegistrationVSpec])
</pre>
<p>but when using <a href="http://github.com/sptz45/sse-guice">sse-guice</a> we can simply write:</p>
<pre lang="scala">
bind[Validator[Registration]].to[RegistrationVSpec]
</pre>
<p>because <code>Manifest</code> also holds any type arguments and <a href="http://github.com/sptz45/sse-guice">sse-guice</a> automatically creates a <code>TypeLiteral</code> when the <code>Manifest</code> contains type arguments.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tzavellas.com/techblog/2010/08/22/making-guice-more-scala-friendly/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using self types for trait composition</title>
		<link>http://www.tzavellas.com/techblog/2009/12/07/using-self-types-for-trait-composition/</link>
		<comments>http://www.tzavellas.com/techblog/2009/12/07/using-self-types-for-trait-composition/#comments</comments>
		<pubDate>Mon, 07 Dec 2009 15:01:37 +0000</pubDate>
		<dc:creator>spiros</dc:creator>
				<category><![CDATA[Scala]]></category>
		<category><![CDATA[trait]]></category>

		<guid isPermaLink="false">http://www.tzavellas.com/techblog/?p=227</guid>
		<description><![CDATA[While using traits in a small Scala project, I finally understood when to use self types. Self types are often characterized by Scala newbies as an incomprehensible language feature with no obvious usage. After coding with traits for a while I understood that self types are an essential information hiding tool for composing traits. I [...]]]></description>
			<content:encoded><![CDATA[<p>While using traits in a small Scala project, I finally understood when to use self types. Self types are often characterized by Scala newbies as an <a href="http://www.naildrivin5.com/scalatour/wiki_pages/ExplcitlyTypedSelfReferences">incomprehensible language feature</a> with no obvious usage. After coding with traits for a while I understood that self types are an essential information hiding tool for composing traits.</p>
<p>I am coding a small JMX library in Scala, similar to <a href="http://static.springsource.org/spring/docs/2.5.x/reference/jmx.html">Spring&#8217;s JMX</a> module and to the <a href="http://github.com/martint/jmxutils">jmxutils</a> library. In my project I have a <code>MBeanInfoAssembler</code> trait, that is a strategy interface, whose role is to create a <code>ModelMBeanInfo</code> from a <code>Class</code>. Implementations of that trait will use reflection to discover the attributes and operations that will be used to export instances of the <code>Class</code> to JMX.</p>
<pre>
trait MBeanInfoAssembler {
  def createMBeanInfo(clazz: Class[_]): ModelMBeanInfo
}
</pre>
<p>The first implementation of the trait was the <code>SimpleMBeanInfoAssembler</code> class which uses reflection and some conventions to discover the attributes and operations.</p>
<pre>
class SimpleMBeanInfoAssembler extends MBeanInfoAssembler {

  def createMBeanInfo(clazz: Class[_]): ModelMBeanInfo =
    new ModelMBeanInfoSupport(clazz.getName,
                              clazz.getSimpleName,
                              attributes(clazz),
                              Array(),
                              operations(clazz),
                              Array())

  private def attributes(c: Class[_]): Array[ModelMBeanAttributeInfo] = {
    //find the attributes from the class using reflection
  }

  private def operations(c: Class[_]): Array[ModelMBeanOperationInfo] = {
    //find the operations from the class using reflection
  }
}
</pre>
<p>In the above code I have removed the implementations of the <code>attributes</code> and <code>operations</code> methods because they are not important for this example. What is important is the <code>createMBeanInfo</code> method which just calls the <code>ModelMBeanInfoSupport</code> constructor with the results of the <code>attributes</code> and <code>operations</code> methods. If we leave the code like this, when we try to provide a second implementation of the <code>MBeanInfoAssembler</code> trait we will probably copy-paste that method&#8217;s code.</p>
<p>In Scala, traits can have concrete methods so our first though is to move the implementation of the <code>createMBeanInfo</code> method to the <code>MBeanInfoAssembler</code> trait. After doing that our trait becomes:</p>
<pre>
trait MBeanInfoAssembler {
  def createMBeanInfo(clazz: Class[_]): ModelMBeanInfo =
    new ModelMBeanInfoSupport(clazz.getName,
                              clazz.getSimpleName,
                              attributes(clazz),
                              Array(),
                              operations(clazz),
                              Array())

  def attributes(c: Class[_]): Array[ModelMBeanAttributeInfo]

  def operations(c: Class[_]): Array[ModelMBeanOperationInfo]
}
</pre>
<p>and the implementation: </p>
<pre>
class SimpleMBeanInfoAssembler extends MBeanInfoAssembler {

  def attributes(c: Class[_]): Array[ModelMBeanAttributeInfo] = {
    //find the attributes from the class using reflection
  }

  def operations(c: Class[_]): Array[ModelMBeanOperationInfo] = {
    //find the operations from the class using reflection
  }
}
</pre>
<p>This refactoring has the obvious advantage of removing the repetition that would be needed to create multiple implementations of <code>MBeanInfoAssembler</code> but also one major disadvantage over our previous code.</p>
<p>In order to support the implementation of the <code>createMBeanInfo</code> method the <code>MBeanInfoAssembler</code> trait gets updated with two new <em>public abstract methods</em> (<code>attributes</code> and <code>operations</code>). Those methods are useless to the clients of the trait, who only want to create a <code>ModelMBeanInfo</code> from a <code>Class</code>, and are there only to support the trait&#8217;s implementation. To correct this defect in our design we need to do another refactoring by introducing a new trait and connecting the two traits together using a self type annotation.</p>
<p>If you are new to Scala you might wonder what is a self type? In the Scala documentation self types are described as a way to <em>&#8220;declare the type of the value <code>this</code> explicitly&#8221;</em> which might be accurate but sounds at least confusing for a newbie like me.</p>
<p>In a well designed object-oriented system we achive reuse and flexibility when our system has lots of small objects that have a single responsibility and are explicitely connected using interfaces that represent the role of the connection. Usually those connections are made using constructor arguments. The power of such system comes from the testability and reusability of the small objects and the flexibility of composing those objects to solve a particular problem.</p>
<p>Since traits in Scala can have code (method implementations), if we want to create an equally well designed and flexible system using traits we need to be able to do the same. The problem is that traits do not have constructors so we need a new construct to declare trait dependencies and also a way to compose traits together. The solution to the first problem are the self type annotations and the solution to the second is multiple inheritance.</p>
<p>In the previous example the <code>MBeanInfoAssembler</code> trait had many responsibilities assigned to it. It must be able to create a <code>ModelMBeanInfo</code> given a <code>Class</code> and it must also extract any metadata in order to find the right attributes and operations for the given <code>Class</code>. We decide to move the second responsibility to a new trait called <code>MBeanMetadataExtractor</code> that has the <code>attributes</code> and <code>operations</code> methods.</p>
<pre>
trait MBeanMetadataExtractor {

  def attributes(c: Class[_]): Array[ModelMBeanAttributeInfo]

  def operations(c: Class[_]): Array[ModelMBeanOperationInfo]
}
</pre>
<p>Now we need to update the <code>MBeanInfoAssembler</code> trait and to somehow connect it to the <code>MBeanMetadataExtractor</code> trait so it can use the <code>attributes</code> and <code>operations</code> methods. To do this we will use a self type annotation.</p>
<pre>
trait MBeanInfoAssembler {

  this: MBeanMetadataExtractor =>

  def createMBeanInfo(clazz: Class[_]): ModelMBeanInfo = {
    new ModelMBeanInfoSupport(clazz.getName,
                              clazz.getSimpleName,
                              attributes(clazz),
                              Array(),
                              operations(clazz),
                              Array())
  }
}
</pre>
<p>The syntax of the self type annotation is <code>this: MBeanMetadataExtractor =></code> and it tells the compiler that a <code>MBeanInfoAssembler</code> can be implemented in a class only if that class also implements the <code>MBeanMetadataExtractor</code> trait. Using this assumption the compiler makes the methods of the <code>MBeanMetadataExtractor</code> available for use in the <code>MBeanInfoAssembler</code> (in our case the <code>attributes</code> and <code>operations</code> methods).</p>
<p>The class <code>SimpleMBeanInfoAssembler</code> now has to implement both <code>MBeanInfoAssembler</code> and <code>MBeanMetadataExtractor</code>.</p>
<pre>
class SimpleMBeanInfoAssembler extends MBeanInfoAssembler with MBeanMetadataExtractor {

  def attributes(c: Class[_]): Array[ModelMBeanAttributeInfo] = {
    //find the attributes from the class using reflection
  }

  def operations(c: Class[_]): Array[ModelMBeanOperationInfo] = {
    //find the operations from the class using reflection
  }
}
</pre>
<p>By doing the above changes we were able to hide the <code>attributes</code> and <code>operations</code> methods from the clients of the <code>MBeanInfoAssembler</code> trait. Obviously those methods exist in the public interface of <code>SimpleMBeanInfoAssembler</code> but in a well designed system other classes will connect with <code>SimpleMBeanInfoAssembler</code> by using one of its traits (interfaces) so this is not a problem.</p>
<p>In conclusion, if we want to move method implementations inside traits then we risk polluting the interface of those traits with abstract methods that support the implementation of the concrete methods and are unrelated with the main responsibility of the trait. A solution to this problem is to move those abstract methods in other traits and compose the traits together using self type annotations and multiple inheritance.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.tzavellas.com/techblog/2009/12/07/using-self-types-for-trait-composition/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
