## Sunday, February 07, 2010

### Scala Self-Type Annotations for Constrained Orthogonality

I talked about orthogonality in design in one of my earlier posts. We had a class Address in Scala and we saw how we can combine it with other orthogonal concerns without polluting the core abstraction. We could do this because Scala offers a host of capabilities to compose smaller abstractions and build larger wholes out of them. A language is orthogonal when it allows such capabilities of composition without overlaps in functionalities between the composing featuresets.

The design of Scala offers many orthogonal features - I showed some of them in my earlier post. The power of mixins for adding orthogonal features ..

val a = new Address(..) with LabelMaker {  override def toLabel = {    //..  }}
and the power of Scala views with implicits ..

object Address {  implicit def AddressToLabelMaker(addr: Address) = new LabelMaker {    def toLabel =    //..  }}
Here Address and LabelMaker are completely unrelated and offers truly orthogonal capabilities when mixed in. However there can be some cases where the mixins themselves are not completely orthogonal to the core abstractions, but really optional extensions to them. In fact the mixins implement some functionalities that may depend on the core abstraction as well. Let's see yet another feature of the Scala type system that makes this modeling wholesome.

Consider the following abstraction for a security trade that takes place in a stock exchange ..

// details ellided for claritycase class Trade(refNo: String, account: String,                  instrument: String, quantity: Int,                 unitPrice: Int) {  // principal value of the trade  def principal = quantity * unitPrice}
For every trade executed on the exchange we need to have a set of tax and fees associated with it. The exact set of tax and fees depend on a number of factors like type of trade, instruments traded, the exchange where it takes place etc. Let's have a couple of tax/fee traits that model this behavior ..

trait Tax {   def calculateTax = //..}  trait Commission {   def calculateCommission = //..}
In the above definitions both methods calculateTax and calculateCommission depends on the trade being executed. One option is to keep them abstract in the above trait and provide their implementations after mixing in with Trade ..

val t = new Trade(..) with Tax with Commission {  // implementations  def calculateTax = principal * 0.2  def calculateCommission = principal * 0.15}
I did it at the instance level. You can very well use this idiom at the class level and define ..

class RichTrade extends Trade with Tax with Commission {  //..}
However the above composition does not clearly bring out the fact that the domain rules mandate that the abstractions Tax and Commission should be constrained to be used with the Trade abstraction only.

Scala offers one way of making this knowledge explicit at the type level .. using self-type annotations ..

trait Tax { this: Trade =>  // refers to principal of trade  def calculateTax = principal * 0.2}  trait Commission { this: Trade =>  // refers to principal of trade  def calculateCommission = principal * 0.15}
The traits are still decoupled. But using Scala's self type annotations you make it explicit that Tax and Commission are meant to be used *only* by mixing them with Trade.

val t = new Trade(..) with Tax with Commissiont.calculateTaxt.calculateCommission
Can I call this constraining the orthogonality of abstractions ? Tax and Commission provide orthogonal attributes to Trade optionally and publish their constraints explicitly in their definitions. It's not much of a difference from the earlier implementations. But I prefer to use this style to make abstractions closer to what the domain speaks.

Anonymous said...

Hello

I really have to say that your blog posts are very interesting!
Like to read them, and I like your scala posts, since its a new language. You show interesting view points.

This composition seems nice. I read a while ago lean architecture and it looks like this. Adding behaviour (or roles) to domain classes.

best regards

Eric said...

I think this is worth pointing to the Data-Context-Interaction paradigm for building systems (http://www.infoq.com/news/2009/05/dci-coplien-reenskau). This is where self-type annotations prove to be very useful as a language feature.

Mats Henricson said...

Really nice blog writeup. I like Scala better for every day!

Unknown said...

I think scala has so many hidden gems and design-friendly features that people have not discovered/learned/understood yet.

Thank you for unlocking them.

J.F. Zarama said...

your blog is a place I visit frequently; I learn from your entries particularly in reference to Scala a language which I like but somewhat gravitate to plain old Java when doing real work; thanks for sharing your insight, ideas and code.

J.F. Zarama said...

your blog is a place I visit frequently; I learn from your entries particularly in reference to Scala a language which I like but somewhat gravitate to plain old Java when doing real work; thanks for sharing your insight, ideas and code.

Alin Popa said...

Great post Debasish. It's the simplest explanation of Self Type Annotations concept that I could find. This really helped me understand them. Thanks.