Scala DCI solution now allows "self" and "this"

62 views
Skip to first unread message

Marc Grue

unread,
Apr 25, 2013, 9:58:20 AM4/25/13
to object-co...@googlegroups.com
Hi all,

For your information, I have added the ability to reference Role Players by "self" or "this" in my latest version of my Scala type macro at Github. This gives us 3 options:

class MoneyTransfer(Source: Account, Destination: Account, amount: Int) extends Context {

  Source.withdraw

  role(Source) {
    def withdraw {
      Source.decreaseBalance(amount)
      Destination.deposit
    }
  }

  role(Destination) {
    def deposit {
      Destination.increaseBalance(amount)
    }
  }
}

class MoneyTransfer(Source: Account, Destination: Account, amount: Int) extends Context {

  Source.withdraw

  role(Source) {
    def withdraw {
      self.decreaseBalance(amount)
      Destination.deposit
    }
  }

  role(Destination) {
    def deposit {
      self.increaseBalance(amount)
    }
  }
}

class MoneyTransfer(Source: Account, Destination: Account, amount: Int) extends Context {

  Source.withdraw

  role(Source) {
    def withdraw {
      this.decreaseBalance(amount)
      Destination.deposit
    }
  }

  role(Destination) {
    def deposit {
      this.increaseBalance(amount)
    }
  }
}

All three options would get transformed into exactly the same:

class MoneyTransfer(Source: Account, Destination: Account, amount: Int) extends Context {

  Source_withdraw()

  private def Source_withdraw() {
    Source.decreaseBalance(amount)
    Destination_deposit()
  }

  private def Destination_deposit() {
    Destination.increaseBalance(amount)
  }
}

Using "this" is a little tricky since "this" would in Scala normally point to the MoneyTransfer instance. But I think it's justifiable to allow a "DCI-idiomatic" use that goes against the Scala-ideomatic use (well it's a keyword there) since if one wants to do DCI in Scala, I presume one is also willing to "think in DCI". And when defining DCI Role methods it's natural to semantically think in terms of "this role".

I have updated the readme on github with some more examples clarifying also how role methods take precedence over instance methods given the same signature and how we can let an object play multiple Roles in a Context.

Cheers,
Marc
Reply all
Reply to author
Forward
0 new messages