<?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 oriented</title>
    <link>http://blog.objectmentor.com/articles/tag/oriented</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>The Seductions of Scala, Part I</title>
      <description>&lt;p&gt;Because of all the recent hoo-ha about &lt;a href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional programming&lt;/a&gt; (&lt;em&gt;e.g.,&lt;/em&gt; as a &amp;#8220;cure&amp;#8221; for the &lt;a href="http://www.technologyreview.com/Infotech/17682/page1/"&gt;multicore problem&lt;/a&gt;), I decided to cast aside my dysfunctional ways and learn one of the FP languages. The question was, which one?&lt;/p&gt;


	&lt;p&gt;My distinguished colleague, &lt;a href="http://www.objectmentor.com/omTeam/feathers_m.html"&gt;Michael Feathers&lt;/a&gt;, has been on a &lt;a href="http://www.haskell.org/"&gt;Haskell&lt;/a&gt; &lt;a href="http://twitter.com/mfeathers"&gt;binge&lt;/a&gt; of late. Haskell is a pure functional language and is probably most interesting as the &amp;#8220;flagship language&amp;#8221; for academic exploration, rather than production use. (That was not meant as flame bait&amp;#8230;) It&amp;#8217;s hard to underestimate the influence Haskell has had on language design, including Java generics, .NET &lt;span class="caps"&gt;LINQ&lt;/span&gt; and F#, &lt;em&gt;etc.&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;However, I decided to learn &lt;a href="http://www.scala-lang.org"&gt;Scala&lt;/a&gt; first, because it is a &lt;span class="caps"&gt;JVM&lt;/span&gt; language that combines object-oriented and functional programming in one language. At ~13 years of age, Java is a bit dated. Scala has the potential of &lt;a href="http://www.adam-bien.com/roller/abien/entry/java_net_javaone_which_programming"&gt;replacing Java&lt;/a&gt; as the principle language of the &lt;span class="caps"&gt;JVM&lt;/span&gt;, an extraordinary piece of engineering that is arguably now more valuable than the language itself. (Note: there is also a .NET version of Scala under development.)&lt;/p&gt;


	&lt;p&gt;Here are some of my observations, divided over three blog posts.&lt;/p&gt;


	&lt;p&gt;First, a few disclaimers. I am a Scala novice, so any flaws in my analysis reflect on me, not Scala! Also, this is by no means an exhaustive analysis of the pros and cons of Scala &lt;em&gt;vs.&lt;/em&gt; other options. Start with the &lt;a href="http://www.scala-lang.org"&gt;Scala website&lt;/a&gt; for more complete information.&lt;/p&gt;


	&lt;h2&gt;A Better &lt;span class="caps"&gt;OOP&lt;/span&gt; Language&lt;/h2&gt;


	&lt;p&gt;Scala works seamlessly with Java. You can invoke Java APIs, extend Java classes and implement Java interfaces. You can even invoke Scala code from Java, once you understand how certain &amp;#8220;Scala-isms&amp;#8221; are translated to Java constructs (&lt;code&gt;javap&lt;/code&gt; is your friend). Scala syntax is more succinct and removes a lot of tedious boilerplate from Java code.&lt;/p&gt;


	&lt;p&gt;For example, the following &lt;code&gt;Person&lt;/code&gt; class in Java:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class Person {
    private String firstName;
    private String lastName;
    private int    age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName  = lastName;
        this.age       = age;
    }

    public void setFirstName(String firstName) { this.firstName = firstName; }
    public void String getFirstName() { return this.firstName; }
    public void setLastName(String lastName) { this.lastName = lastName; }
    public void String getLastName() { return this.lastName; }
    public void setAge(int age) { this.age = age; }
    public void int getAge() { return this.age; }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;can be written in Scala thusly:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class Person(var firstName: String, var lastName: String, var age: Int)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Yes, that&amp;#8217;s it. The constructor is the argument list to the class, where each parameter is declared as a variable (&lt;code&gt;var&lt;/code&gt; keyword). It automatically generates the &lt;em&gt;equivalent&lt;/em&gt; of getter and setter methods, meaning they look like Ruby-style attribute accessors; the getter is &lt;code&gt;foo&lt;/code&gt; instead of &lt;code&gt;getFoo&lt;/code&gt; and the setter is &lt;code&gt;foo = &lt;/code&gt; instead of &lt;code&gt;setFoo&lt;/code&gt;. Actually, the setter function is really &lt;code&gt;foo_=&lt;/code&gt;, but Scala lets you use the &lt;code&gt;foo = &lt;/code&gt; &lt;em&gt;sugar&lt;/em&gt;.&lt;/p&gt;


	&lt;p&gt;Lots of other well designed conventions allow the language to define almost everything as a method, yet support forms of syntactic sugar like the illusion of operator overloading, Ruby-like &lt;span class="caps"&gt;DSL&lt;/span&gt;&amp;#8217;s, &lt;em&gt;etc.&lt;/em&gt;&lt;/p&gt;


	&lt;p&gt;You also get fewer semicolons, no requirements tying package and class definitions to the file system structure, type inference, multi-valued returns (tuples), and a better type and generics model.&lt;/p&gt;


	&lt;p&gt;One of the biggest deficiencies of Java is the lack of a complete &lt;em&gt;mixin&lt;/em&gt; model. Mixins are small, focused (think &lt;a href="http://www.objectmentor.com/resources/articles/srp.pdf"&gt;Single Responsibility Principle&lt;/a&gt; ...) bits of state and behavior that can be added to classes (or objects) to extend them as needed. In a language like C++, you can use multiple inheritance for mixins. Because Java only supports single inheritance and interfaces, which can&amp;#8217;t have any state and behavior, implementing a mixin-based design has always required various hacks. &lt;a href="http://www.aosd.net"&gt;Aspect-Oriented Programming&lt;/a&gt; is also one &lt;em&gt;partial&lt;/em&gt; solution to this problem.&lt;/p&gt;


	&lt;p&gt;The most exciting &lt;span class="caps"&gt;OOP&lt;/span&gt; enhancement Scala brings is its support for  &lt;a href="http://www.scala-lang.org/intro/traits.html"&gt;Traits&lt;/a&gt;, a concept first described &lt;a href="http://portal.acm.org/citation.cfm?id=1119479.1119483"&gt;here&lt;/a&gt;. Traits support Mixins (and other design techniques) through composition rather than inheritance. You could think of traits as interfaces with implementations. They work a lot like Ruby modules.&lt;/p&gt;


	&lt;p&gt;Here is an example of the &lt;a href="http://en.wikipedia.org/wiki/Observer_pattern"&gt;Observer Pattern&lt;/a&gt; written as traits, where they are used to monitor changes to a bank account balance. First, here are reusable &lt;code&gt;Subject&lt;/code&gt; and &lt;code&gt;Observer&lt;/code&gt; traits.&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;

	&lt;p&gt;In Scala, generics are declared with square brackets, &lt;code&gt;[...]&lt;/code&gt;, rather than angled brackets, &lt;code&gt;&amp;lt;...&amp;gt;&lt;/code&gt;. Method definitions begin with the &lt;code&gt;def&lt;/code&gt; keyword. The &lt;code&gt;Observer&lt;/code&gt; trait defines one abstract method, which is called by the &lt;code&gt;Subject&lt;/code&gt; to notify the observer of changes. The &lt;code&gt;Subject&lt;/code&gt; is passed to the &lt;code&gt;Observer&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;This trait looks exactly like a Java interface. In fact, that&amp;#8217;s how traits are represented in Java byte code. If the trait has state and behavior, like &lt;code&gt;Subject&lt;/code&gt;, the byte code representation involves additional elements.&lt;/p&gt;


	&lt;p&gt;The &lt;code&gt;Subject&lt;/code&gt; trait is more complex. The strange line, &lt;code&gt;this: S =&amp;gt; &lt;/code&gt;, is called a &lt;em&gt;self type&lt;/em&gt; declaration. It tells the compiler that whenever &lt;code&gt;this&lt;/code&gt; is referenced in the trait, treat its type as &lt;code&gt;S&lt;/code&gt;, rather than &lt;code&gt;Subject[S]&lt;/code&gt;. Without this declaration, the call to &lt;code&gt;receiveUpdate&lt;/code&gt; in the &lt;code&gt;notifyObservers&lt;/code&gt; method would not compile, because it would attempt to pass a &lt;code&gt;Subject[S]&lt;/code&gt; object, rather than a &lt;code&gt;S&lt;/code&gt; object. The self type declaration solves this problem.&lt;/p&gt;


	&lt;p&gt;The next line creates a private list of observers, initialized to &lt;code&gt;Nil&lt;/code&gt;, which is an empty list. Variable declarations are &lt;code&gt;name: type&lt;/code&gt;. Why didn&amp;#8217;t they follow Java conventions, &lt;em&gt;i.e.,&lt;/em&gt; &lt;code&gt;type name&lt;/code&gt;? Because this syntax makes the code easier to parse when &lt;em&gt;type inference&lt;/em&gt; is used, meaning where the explicit &lt;code&gt;:type&lt;/code&gt; is omitted and inferred.&lt;/p&gt;


	&lt;p&gt;In fact, I&amp;#8217;m using type inference for all the method declarations, because the compiler can figure out what each method returns, in my examples. In this case, they all return type &lt;code&gt;Unit&lt;/code&gt;, the equivalent of Java&amp;#8217;s &lt;code&gt;void&lt;/code&gt;. (The name &lt;code&gt;Unit&lt;/code&gt; is a common term in functional languages.)&lt;/p&gt;


	&lt;p&gt;The third line defines a method for adding a new observer to the list. Notice that concrete method definitions are of the form&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def methodName(parameter: type, ...) = {
    method body
}  
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;In this case, because there is only one line, I dispensed with the &lt;code&gt;{...}&lt;/code&gt;. The equals sign before the body emphasizes the functional nature of scala, that all methods are objects, too. We&amp;#8217;ll revisit this in a moment and in the next post.&lt;/p&gt;


	&lt;p&gt;The method body prepends the new observer object to the existing list. Actually, a new list is created. The &lt;code&gt;::&lt;/code&gt; operator, called &amp;#8220;cons&amp;#8221;, &lt;em&gt;binds to the right&lt;/em&gt;. This &amp;#8220;operator&amp;#8221; is really a method call, which could actually be written like this, &lt;code&gt;observers.::(observer)&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;Our final method in &lt;code&gt;Subject&lt;/code&gt; is &lt;code&gt;notifyObservers&lt;/code&gt;. It iterates through observers and invokes the block &lt;code&gt;observer.receiveUpdate(this)&lt;/code&gt; on each observer. The &lt;code&gt;_&lt;/code&gt; evaluates to the current observer reference. For comparison, in Ruby, you would define this method like so:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def notifyObservers() 
    @observers.each { |o| o.receiveUpdate(self) }
end
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Okay, let&amp;#8217;s look at how you would actually use these traits. First, our &amp;#8220;plain-old Scala object&amp;#8221; (POSO) &lt;code&gt;Account&lt;/code&gt;.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class Account(initialBalance: Double) {
    private var currentBalance = initialBalance
    def balance = currentBalance
    def deposit(amount: Double)  = currentBalance += amount
    def withdraw(amount: Double) = currentBalance -= amount
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Hopefully, this is self explanatory, except for two things. First, recall that the whole class declaration is actually the constructor, which is why we have an &lt;code&gt;initialBalance: Double&lt;/code&gt; parameter on &lt;code&gt;Account&lt;/code&gt;. This looks strange to the Java-trained eye, but it actually works well and is another example of Scala&amp;#8217;s economy. (You can define multiple constructors, but I won&amp;#8217;t go into that here&amp;#8230;).&lt;/p&gt;


	&lt;p&gt;Second, note that I omitted the parentheses when I defined the &lt;code&gt;balance&lt;/code&gt; &amp;#8220;getter&amp;#8221; method. This supports the &lt;em&gt;uniform access principle&lt;/em&gt;. Clients will simply call &lt;code&gt;myAccount.balance&lt;/code&gt;, without parentheses and I could redefine &lt;code&gt;balance&lt;/code&gt; to be a &lt;code&gt;var&lt;/code&gt; or &lt;code&gt;val&lt;/code&gt; and the client code would not have to change!&lt;/p&gt;


	&lt;p&gt;Next, a subclass that supports observation.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class ObservedAccount(initialBalance: Double) extends Account(initialBalance) with Subject[Account] {
    override def deposit(amount: Double) = {
        super.deposit(amount)
        notifyObservers()
    }
    override def withdraw(amount: Double) = {
        super.withdraw(amount)
        notifyObservers()
    }
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;with&lt;/code&gt; keyword is how a trait is used, much the way that you &lt;code&gt;implement&lt;/code&gt; an interface in Java, but now you don&amp;#8217;t have to implement the interface&amp;#8217;s methods. We&amp;#8217;ve already done that.&lt;/p&gt;


	&lt;p&gt;Note that the expression, &lt;code&gt;ObservedAccount(initialBalance: Double) extends Account(initialBalance)&lt;/code&gt;, not only defines the (single) inheritance relationship, it also functions as the constructor&amp;#8217;s call to &lt;code&gt;super(initialBalance)&lt;/code&gt;, so that &lt;code&gt;Account&lt;/code&gt; is properly initialized.&lt;/p&gt;


	&lt;p&gt;Next, we have to override the &lt;code&gt;deposit&lt;/code&gt; and &lt;code&gt;withdraw&lt;/code&gt; methods, calling the parent methods and then invoking &lt;code&gt;notifyObservers&lt;/code&gt;. Anytime you override a concrete method, scala requires the &lt;code&gt;override&lt;/code&gt; keyword. This tells you unambiguously that you are overriding a method and the Scala compiler throws an error if you aren&amp;#8217;t actually overriding a method, &lt;em&gt;e.g.,&lt;/em&gt; because of a typo. Hence, the keyword is much more reliable (and hence useful&amp;#8230;) than Java&amp;#8217;s &lt;code&gt;@Override&lt;/code&gt; annotation.&lt;/p&gt;


	&lt;p&gt;Finally, here is an &lt;code&gt;Observer&lt;/code&gt; that prints to stdout when the balance changes.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
class AccountReporter extends Observer[Account] {
    def receiveUpdate(account: Account) =
        println("Observed balance change: "+account.balance)
}
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Rather than use &lt;code&gt;with&lt;/code&gt;, I just extend the &lt;code&gt;Observer&lt;/code&gt; trait, because I don&amp;#8217;t have another parent class.&lt;/p&gt;


	&lt;p&gt;Here&amp;#8217;s some code to test what we&amp;#8217;ve done.&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
def changingBalance(account: Account) = {
    println("==== Starting balance: " + account.balance)
    println("Depositing $10.0")
    account.deposit(10.0)
    println("new balance: " + account.balance)
    println("Withdrawing $5.60")
    account.withdraw(5.6)
    println("new balance: " + account.balance)
}

var a = new Account(0.0)
changingBalance(a)

var oa = new ObservedAccount(0.0)
changingBalance(oa)
oa.addObserver(new AccountReporter)
changingBalance(oa)
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Which prints out:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
==== Starting balance: 0.0
Depositing $10.0
new balance: 10.0
Withdrawing $5.60
new balance: 4.4
==== Starting balance: 0.0
Depositing $10.0
new balance: 10.0
Withdrawing $5.60
new balance: 4.4
==== Starting balance: 4.4
Depositing $10.0
Observed balance change: 14.4
new balance: 14.4
Withdrawing $5.60
Observed balance change: 8.8
new balance: 8.8
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;p&gt;Note that we only observe the last transaction.&lt;/p&gt;


	&lt;p&gt;&lt;a href="http://www.scala-lang.org/downloads/index.html"&gt;Download Scala&lt;/a&gt; and try it out. Put all this code in one &lt;code&gt;observer.scala&lt;/code&gt; file, for example, and run the command:&lt;/p&gt;


&lt;pre&gt;
    &lt;code&gt;
scala observer.scala
    &lt;/code&gt;
&lt;/pre&gt;

	&lt;h2&gt;But Wait, There&amp;#8217;s More!&lt;/h2&gt;


	&lt;p&gt;In the next post, I&amp;#8217;ll look at Scala&amp;#8217;s support for Functional Programming and why OO programmers should find it interesting. In the third post, I&amp;#8217;ll look at the specific case of concurrent programming in Scala and make some concluding observations of the pros and cons of Scala.&lt;/p&gt;


	&lt;p&gt;For now, here are some references for more information.&lt;/p&gt;


	&lt;ul&gt;
	&lt;li&gt;The &lt;a href="http://www.scala-lang.org"&gt;Scala website&lt;/a&gt;, for downloads, documentation, mailing lists, &lt;em&gt;etc.&lt;/em&gt;&lt;/li&gt;
		&lt;li&gt;Ted Neward&amp;#8217;s excellent &lt;a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=scala+neward"&gt;multipart introduction&lt;/a&gt; to Scala at &lt;a href="http://www.ibm.com/developerworks"&gt;developerWorks&lt;/a&gt;.&lt;/li&gt;
		&lt;li&gt;The forthcoming &lt;a href="http://www.artima.com/shop/programming_in_scala"&gt;Programming in Scala&lt;/a&gt; book.&lt;/li&gt;
	&lt;/ul&gt;</description>
      <pubDate>Sun, 03 Aug 2008 15:30:00 +0000</pubDate>
      <guid isPermaLink="false">urn:uuid:d4a4acbf-e300-4146-83c7-0536785997e1</guid>
      <author>Dean Wampler</author>
      <link>http://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i</link>
      <category>Dean's Deprecations</category>
      <category>Design Principles</category>
      <category>Java</category>
      <category>Scala</category>
      <category>statically</category>
      <category>typed</category>
      <category>dynamically</category>
      <category>OOP</category>
      <category>FP</category>
      <category>functional</category>
      <category>object</category>
      <category>oriented</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>
  </channel>
</rss>
