<?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() &#187; trait</title>
	<atom:link href="http://www.tzavellas.com/techblog/tag/trait/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>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>

