This blog is no longer being maintained, please go to The missing link of Agile instead

Monday, June 29, 2009

Design patterns in Scala: Command

Many people say that Command pattern in languages of functional paradigm is not really a pattern but actually an inherent feature of a language itself. I don't know about other languages but in Scala it is not entirely true. While it is rather quite easy to come up with Command pattern implementation - you write a closure and it's done ;) - but variety of possibilities that language gives you is pretty amazing.

Let's start from the very beginning.
I believe that the three following points represent the most important aspects to consider when choosing appropriate implementation of Command Pattern in Scala.
  • what the signature of "Command" used as a parameter looks like
  • how do you construct a "Command" instance
  • how do you assign a "Command" instance to a value
The most straightforward solution to Command pattern implementation is:

// Example 1
def command(i : Int) = println(i);

// Usage:
// 1
def invoker(cmd : Int => Unit) = cmd(1)
// 2
invoker(command _)
// or
// 3
val savedCommand = command _

However concise and elegant it has important shortcomings. Firstly you get very wide and crude interface - (Int) => (Unit) means nothing after all. You won't communicate a lot of information with that and a user can pass any command to an "invoker" method (including ShutDownReactor procedure ;]). The second thing is a nasty wildcard you have to use when assigning an instance of a command to a variable. (which you may optionally use in 2. - and if you don't compiler will do it for you).

You can have a bit cleaner solution with following piece of code.

// Example 1
def command = (i : Int) => println(i);

// Usage:
// 1
def invoker(cmd : Int => Unit) = cmd(1)
// 2 a) prepared command
// 2 b) ad hoc command
invoker((i : Int) => println(i))
// 3
val savedCommand = command

The method presented above is actually the partially applied function of a function from the previous example. You gain the advantage of not writing the '_' (placeholder) when assigning an instance to a variable - what IMHO both simplifies and makes it a little less magical :). And if you wonder what would happen if you've added it anyway, the answer is simple - you'd get a partially applied partially applied function ;P with following signature:

() => (Int) => Unit

To solve the issue of wide interface you might use the more classical example of a Command pattern with a bit of functional language coolness on the top ;)

// Example 3
trait Command { def apply(i : Int) }
object DefaultCommand extends Command { def apply(i : Int) = println(i) }

// Usage:
// 1
def invoker(cmd : Command) = cmd(1)
// 2
// 2 b) ad hoc command construction
invoker(new Command { def apply(i : Int) = println(i) })
// 3
val savedCommand : Command = DefaultCommand

Pretty nice - it gives you very clean nice interface with possibility of extending it with whatever responsibility you like (what was obviously missing in first two examples). Nothing comes for free though - the ad hoc construction of a command class is more verbose than a simple command function.

If you're cra^M^M^Mbrave enough you might even try something like this:

class CrazyCommand extends (Int => Unit) { def apply(i : Int) = println(i) }

And now the nice thing is that you may both use it as in 3. example and also pass it to a function defined in previous code snippets. Though I have no idea why anyone would like to do that ;)

While I'm at it I'd remind you about a cool Scala feature that let you extend class behaviour at instantiation and thus you can do the same with:

new Command with (Int => Unit) { def apply(i: Int) = println(i) }

Fun Exercise! ;)

type CoolCommand = (Int => Unit) with (String => Unit)

def coolFunction(cmd : CoolCommand) { cmd(1); cmd("one") }

The implementation of a class that may be passed as a parameter to a 'coolFunction' is left to a reader and may be impossible :P

Thursday, June 18, 2009

Design patterns in Scala: Singleton

I am always keen on improving my knowledge of Scala. Second thing is that I really enjoy to share what I learned with everyone (I do really hope people eventually gain much more interest in Scala :D). That's why I decided to make series on .. GoF design patterns in Scala.

For starters I've chosen our old friend - Singleton. Let's go then!

object Singleton

// Usage:
val singleton = Singleton

Done! Thx for reading..

..just kidding, let's dig a little deeper into that.

You are probably curious about thread safety of this solution. The actual code generated in bytecode and decompiled with JAD looks like that:

public final class Singleton$
implements ScalaObject

public Singleton$()

public int $tag()
throws RemoteException
return scala.ScalaObject.class.$tag(this);

public static final Singleton$ MODULE$ = this;

new Singleton$();

There are 3 things to consider:
  • Singleton object is initialized in static block so thread safety is guaranteed by JVM

  • Every time you reference Singleton object in your code, Scala compiler translates this call into 'Singleton$.MODULE$',

  • This implemention has also quite cool semantics of access modifiers (which is a bit more advanced topic; search for 'companion module' to learn more).

An important thing to notice is that Singleton is eagerly initialized so if you try:
it'll cause initialization to be performed. For now I have no idea how to force 'object' in Scala to be lazy initialized. The only solution I came up with would be:

// Incorrect (see the bottom of article)
class LazySingleton private () {
def apply() = this

// Correct
class LazySingleton private () {

object LazySingleton {
lazy val INSTANCE = new LazySingleton();
def apply() = INSTANCE

// Usage:
val singleton = Singleton()

The trick is to make default constructor private and have apply method of 'object' class type return the only instance of LazySingleton class.

Disadvantage of second implementation is a small but noticable difference in usage. First - requires '()' [apply[ operator to be used. Second - it returns different type of class depending on whether '()' is used (class LazySingleton) or not (object LazySingleton):

scala> C()
res1: C = C@304648

scala> C
res2: C.type = C$@1b9e7fc

Modified 2009-06-23: Previous implemention of lazy singleton was incorrect and led to wrong conclusions.

Wroclaw Area Situated Scala Enthusiasts group established !!

I am happy to announce that Przemysław Pokrywka and Piotr Adamski established WrASSE (Wroclaw Area Situated Scala Enthusiasts) here in Wroclaw!! It's really amazing to meet people that care about Scala and hope for this great language to become the next Java :D
If you're curious how this image is connected to this post visit WrASSE discussion group

There are regular meetings planned in the (hopefully near) future, but a group is veeery young and all your great ideas for WraSSE are welcome!

If you are Scala fun (slash zealot .. whatever ;)) and do care about your professional future (which would be Scala mostly ;P) I encourage you to join this group and actively participate!

Monday, June 15, 2009

My two cents on Agile adoption

Agile is like teenage sex, everybody is talking about it, most are not doing it and those that are doing it, are doing it wrong.
paraphrase of James O. Coplien 1
So a guy - let's call him John - wants his company to be hip'n'cool and be Agile. He goes by the book, put some things into work and yeeeeaahh.. nooo.. - people scream, tools don't work, tests breaks, client's pissed.. He begins ranting on Agile being unable to deliver him its expected awesomeness.. trying harder and harder.. right until it breaks completely.


You know Albert Einstein was a pretty smarty guy? He actually said:
Insanity: doing the same thing over and over again and expecting different results.
That is exaaactly what John is doing. I am honestly amazed how vast majority of people approach this problem. It may be characterized as: "Doesn't work? Let's ditch it". I mean.. WTF? Are they really that lazy to make any alterations? It's either that or they thought they'd be anointed by Holy Ghost with Agile skills.. I mean be reasonable you don't expect to become Software Architect one month after graduation...

However there's still a question to answer: "What might be a better solution than moving back to RUP" (which is bad and stinks and even IBM knows it :P).

You know how TDD cycle looks like don't you:

What if I've shown you something quite similar:

First - move slowly, take small steps. Otherwise you won't know what works and what doesn't, you will overwhelm your team2 with too much change and slow down development process down to nothing.

Second - use feedback! You're getting negative - may it be - in TDD red tests have the same value as green ones.

Third - don't expect to become Agile star overnight.

It requires time.
It requires effort.
It may deliver profits.
If you're not determined to take a risk don't put blame on a process. Just admit it.

1. From his superb presentation on DCI.

2. "Gently introduce change to a team. Don't expect things to suddenly change overnight." Ryan XXX [don't know last name]

Thursday, June 04, 2009

Been busy preparing presentation "Scala for practitioners"

Last month it was pretty silent on this blog and I got to say sorry for that. It was quite busy month for me and I couldn't even find the time to tweet not mentioning blogging. The most important thing that came out to live during this time was a presentation - on probably the best language in the world - titled: "Scala for practitioners". I gave it for the first time yesterday in Power Media S.A. (which is the company I'm currently cooperating with as a freelancer :)) and you can find the project I used during the presention here on github. The primary goal was to show Scala as language having real business value here and now, being really close to get significant impact in software projects. From all the feedback that I've gathered I guess I can safely state - it was a success! :D Next I'm planning on giving this presentation on Wroclaw JUG. It actually needs some minor corrections (what again will probably cause absence of new posts on this blog .. ;P) but I really hope it will trigger more enthusiasm for Scala in Java community. I'm also thinking on doing some screencasts on Scala but the exact idea is not fully matured yet, so all tips are welcome!

For all of you not to feel like you've lost another 2 minutes of your life reading this post:
Mindblowing example of how cool is regexp matching in Scala (if you think you've seen it try checking it out anyways - it's not the same old regexp matching example :P).