Tuesday, January 26, 2010

Dependency Injection in Scala and some other stuff

My new  found love is the Java Spring framework. I initially looked at the SpringFramework for .NET and thought it was really good and well designed. But then for a pet project of mine, my friend promised to help me given the project would be on the JVM. So we decided that we shall consider Scala as the language of choice on the JVM. Now, I know how I can do DI using Spring Container in Java. So I was wondering if I could do the same in Scala. Turns out, it is not so difficult after all (so far).

For my scala development environment, I played with Eclipse, IntelliJ Community Edition and then Netbeans. So far, Netbeans has the best support for Scala in the form of IDE integration. There are some issues with it but then it is not all too bad. One initial issue was that even though the Spring JAR files were in my class path, the netbeans editor complained that it could locate the Spring Jars. The error message was something like “the value springframework is not a member of the package org”. Turns out, if you clean and build the project, it would build successfully but the editor keeps complaining. The Netbeans wiki talked about having some “Reset Scala Parser” item on the context menu but I am so dumb that I still could not find it. So if there is no reset trigger then how about we close and start the IDE. And it works! For now, since I am using nightly builds (follow the wiki link here http://wiki.netbeans.org/Scala68v1) I would not mind these minor issues. But let me tell you, I spent a whole evening trying to figure out which is the best IDE for latest Scala and the winner is Netbeans, without any question.

Now at the time I created my sample project, I made sure that I check the settings in Netbeans project creation wizard which allows me to copy all my libraries into a common folder such that it would be easier when working as a team. Then I added the following files from the Spring Distribution.


Apart from these, I added commons-logging jar too.

Following code shows how you can use Spring within scala. So lets say I have an interface Sample. (which are almost traits in Scala). And I have a concrete implementation ScalaImpl. Follow the code carefully and with some fundamental understanding of Spring  framework, you should be all set.

/** Main.scala **/
package tryscala
import org.springframework.context.support.FileSystemXmlApplicationContext

object Main {

* @param args the command line arguments
def main(args: Array[String]): Unit = {
val fs = new FileSystemXmlApplicationContext("Configs\\Spring.xml")
val sample = fs.getBean(classOf[Sample]).asInstanceOf[Sample]
println(sample sayHello)

/** Sample.scala **/
package tryscala

trait Sample {
def sayHello(): String

/** SampleImpl.scala"
package tryscala

class SampleImpl(var firstName:String) extends Sample {
def sayHello() = "Welcome to Scala : " + firstName

The spring configuration file (Configs\\Spring.xml) is shown below.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="sample" class="tryscala.SampleImpl">
<constructor-arg name="firstName" value="Krishna Vangapandu"/>

I hope to be able to share more about what we are doing and how Scala effects us, as we move on.

Thursday, January 14, 2010

Rhino Mocks : How to mock read-only properties.

As part of my never-ending quest to do something big, I started working on an application for which I am learning to use Rhino Mocks and I thought it would make a small and easy example to understand mocks. I have not particularly followed TDD approach so far, but anyway here is my attempt to show how you would use Rhino Mocks to stub/mock (am yet to understand when to use what…I mean i know the difference … just did not develop enough maturity in that aspect).

Let us say I have some interface which is as simple as shown below.

public interface IColumn {
public string Name { get; }
public string DataType { get; }

Now if I were to mock/stub this interface, I had some problems with Rhino Mocks throwing exceptions on how the property should have a getter/setter when I was trying to configure the mock such that whenever Name property is accessed you should return "Krishna Bhargava" and for DataType you should return "System.String". I tried different mechanims like using Expect.On(col).Call(it.Name).Return("Krishna Bhargava") or tried to define property behavior (PropertyBehavior()). Finally after struggling for an hour, looking at various examples online from good people like you and me, I was able to come up with proper code that can generate a stub for the column defined in this interface. The code snippet shows how you can use Rhino Mocks (which i think the most convenient framework - i tried Moq (somehow it does not click with me), NUnit.Mocks( too much ground work)) so that u can generate stubs for read-only properties! Unfortunately at the moment, I cannot comment much on the Rhino Mocks classes .. I hope the code snippet is easy to understand.

private IColumn MockColumn(string name, string type)
IColumn col = MockRepository.GenerateStub();
col.Stub(it => it.DataType).Return(Type.GetType(type));
col.Stub(it => it.Name).Return(name);
return col;

you can later use this method as shown below

public void ColumnStubNameCanBeSet()
IColumn col = MockColumn("name", "String.String");
Assert.AreEqual(typeof(string), col.DataType);

/*a little bit more real world usage of a column stub is shown below. */
public void ValuesCanBeSetOnARecord()
IRecord record = new Record(); //NOT DESCRIBED in this blog, but this is my personal class....
record.SetValue(MockColumn("name", "System.String"), "Krishna Vangapandu");
record.SetValue(MockColumn("age", "System.Int32"), 25);
Assert.AreEqual("Krishna Vangapandu",record.Value("name"));
Assert.AreEqual(25, record.Value("age"));

And by the way, Castle Windsor has the best and easiest configuration schema in all the IoC containers I played with. I personally like Unity Container but its configuration is a mess and over-engineered. I will try to post an implementation of Observer-Pattern where observers and observables are linked with pure configuration - the best use I made of IoC container so far!