Saturday, December 13, 2008

Non-Functional

I've started to look at the Scala programming language. It's a very interesting language created by Martin Odersky who was responsible for addition of Generics to Java. It is both an object-oriented and a functional language. This makes it incredibly powerful, and incredible difficult at the same time.

The Awesome


It has two features that I find are incredible powerful. The first is Scala's solution to the multiple inheritance problem. A piece of functionality can be placed into a trait, which is akin to a interface, but may contain implementation. Now an object can gain pieces of functionality, without having either a polluted hierarchy or a set of interfaces with repeat of the functionality throughout the code base.

The only way to really accomplish this in Java was to use Aspects (which I do happen to like, for this very reason), but there are a variety of libraries to do this, all of which do it in their own way (AspectJ, AspectWerks, etc).

Secondly, Scala provides the ability to create your own language features. One of example of this (courtesy of Ted Neward) is with exception handling:

/ This is Scala
object Application
{
def generateException()
{
System.out.println("Generating exception...");
throw new Exception("Generated exception");
}

def main(args : Array[String])
{
tryWithLogging // This is not part of the language
{
generateException
}
System.out.println("Exiting main()");
}

def tryWithLogging (s: => Unit) {
try {
s
}
catch {
case ex: Exception =>
// where would you like to log this?
// I choose the console window, for now
ex.printStackTrace()
}
}
}

We've actually created a function which takes a void function as it's argument. Due to the way Scala allows us to call functions, it can look like a part of the language. This is really powerful if you are in the business of creating Domain-Specific languages.

The Difficult

Again, Scala mixes object-oriented and functional paradigms. The functional aspect has me in a bit of an intellectual twist. I need to unwrap the OO part of my brain, and try and think like a functional coder. I was halfway there when I was doing a lot of Javascript programming, however I was busy doing what everyone else was doing: enhancing what OO capabilities are in the language.

Functional programming is different, and takes a different mindset. I'm doing some reading on the subject, but it's a struggle. I have to battle some long-set ideas in my own thinking.

Still, there has been an interesting explosion in languages, and it's a rather exiting time to be a programmer.

0 comments: