
Polyglot Learning
We are going to learn Scala, Lift, Groovy, Grails, Ruby and Rails, iPhone, and Android app development using a simple application.
We will develop a virtual queuing application. When you go to a post office or to DMV, you have to take a number token that places you in a queue. The people providing the service, call out the next number that they can service and the queue moves forward eventually your turn comes and your number is called out.
We will create a system that will have these queues on the cloud. A service provider can create a queue and the queue is available on the cloud. A queue can be discovered in several ways – the creator of the queue can assign a unique name to the queue, or the queue can be identified based on the physical location where the people waiting in the queue will get the service.
A queue can be accessed either through a mobile device or through a web browser. The queue will provide the ability for a customer to get into the queue by drawing out a token. The customer will have the ability to see how fast the queue is moving (based on statistics that the system will collect for the past hour or so). The customer will be given an estimate about how much longer they will have to wait for beft ore their turn. They will get an alarm when they get closer to their turn so they can plan and get ready. For example, if one is at a grocery store, they can get in the queue but continue shopping. When they are a couple of minutes away from their turn they can walk up to the deli counter.
The people servicing the queue will have the ability to select the next person in line. Once they select the next person in line, an announcement will be made calling the token number or the identifier for the next token. The queue will automatically advance to the next number. The administrator of the queue will have the ability to reset the queue to start afresh cycle of tokens.
A queue can be accessed from any mobile device or from the web. When using a mobile device, the location of the device will provide a clue about the active queues at that location. If there are multiple queues at a given location (for example a grocery store might have a bank, a butcher shop, and a deli; each department will have its own queue).
Let’s start by designing this application a bit. The goal of this blog is to learn new languages and technologies as we go along. On those lines, we will build the system incrementally. We will design a little piece of functionality, code a little, and explore alternative ways of implementing the same functionality. The idea is not to explore all the features of these languages but just those that we come across during the course of developing the application. Hopefully, the application will expose us to enough of the language and technology that it will become easier to pick up the rest as they are needed
In this spirit, let’s start with a NumberDispenser class. This class will hold a counter – the next number to be dispensed. It will have methods that will dispense the next number, will let us just peek at the next number without dispensing it, and will allow us to reset the counter to a new number.
class NumberDispenser(startingNumber: Int) {
private var nextNumber = startingNumber;
// Methods of this class
def dispense : Int = {nextNumber += 1;nextNumber - 1}
def peek = nextNumber
def reset (resetTo : Int) {nextNumber = resetTo}
}
Let’s look at this class, scala class is listed just like java with a class keyword. The only interesting thing in this declaration is that there are parameters that are passed to the definition of the class in parentheses. These are called class parameters and the scala compiler will take these parameters and pass it to a primary constructor that it will create. So, one does not have to write a constructor by hand. In order to create an object of this class, one would use the new keyword just like in java.
new NumberDispenser(100)
what else is interesting in this class? There is a private data member that holds the state of the class – the next number to dispense. Note that in Scala uses type inference to deduce the data type for the variable. It’s able to do that since we initialize the variable using the class parameters which have been declared as Int.
Besides the data variable there are three methods that the class exposes as its behavior. Let’s examine these. A Scala method is declared with a “def” keyword, which I assume stands for define. Following def is the name of the method separated by a colon and then the return type of the method. The return type is optional and compiler can use type inference to deduce the return type of a function. In the above class this is illustrated by providing an explicit return type for the dispense method but the peek method lets the compiler deduce the return type. Another interesting point to mention here is that there is no need for an explicit return statement. The value of the last expression in a method becomes the return value. In case of dispense method the last expression is nextNumber – 1 and in case of the peek method the last statement is nextNumber. Also notice that if a method has only one statement there is no need to provide curly braces.
Now consider the reset method. This method does not return any value but has a side effect where it changes the next number that will be returned next. The return type of such methods is Unit. A short form of saying that the method does not return anything useful but is invoked just for its side effect is to remove the = sign after the method name and return type declaration. When there is no = sign before a methods body, it ignores the value calculated by the last expression of the method.
Testing
Lets write a test class to test our simple NumberDispenser. In Scala you have multiple choices of test frameworks to use. You can use the ever so popular JUnit framework, but you can also write your test cases in TestNG or in pure scala based testing frameworks like ScalaTest, specs and ScalaCheck.
For today’s blog we will start writing a test case in JUnit and then show how the same test case can be written in ScalaTest.
Here is the JUnit test class and it is self explanatory so we will not go further into it.
import org.junit.Assert.assertEquals
import org.junit.{Before, Test}
class NumberDispenserTest {
private val numberDispenser = new NumberDispenser(100)
@Before
def setup() {
numberDispenser.reset(200)
}
@Test
def dispense() {
assertEquals(200, numberDispenser.dispense)
assertEquals(201, numberDispenser.dispense)
assertEquals(202, numberDispenser.peek)
}
@Test
def peek() {
assertEquals(200, numberDispenser.peek)
assertEquals(200, numberDispenser.peek)
numberDispenser.dispense
numberDispenser.dispense
assertEquals(202, numberDispenser.peek)
}
@Test
def reset() {
assertEquals(200, numberDispenser.peek)
}
}
And here is the same test case written in ScalaTest.
import org.scalatest.{BeforeAndAfter, FunSuite}
import org.scalatest.junit.JUnitRunner
import org.junit.runner.RunWith
@RunWith(classOf[JUnitRunner])
class NumberDispenserSuiteTest extends FunSuite with BeforeAndAfter {
private val numberDispenser = new NumberDispenser(100)
before {
numberDispenser reset 200
}
test("dispense") {
assert(200 == numberDispenser.dispense)
assert(201 == numberDispenser.dispense)
assert(202 == numberDispenser.peek)
}
test("peek") {
assert(200 == numberDispenser.peek)
assert(200 == numberDispenser.peek)
numberDispenser.dispense
numberDispenser.dispense
assert(202 == numberDispenser.peek)
}
test ("reset") {
assert(200 == numberDispenser.peek)
}
}
Using ScalaTest’s FunSuite test suite, tests can be defined as function values. Let’s explore this a little more. Our test case “NumberDispenserSuite” extends a ScalaTest Framework construct called FunSuite. The “extends” keyword is similar to the Java extends keyword and defines a subclass-superclass relationship. However, FunSuite is not exactly a class. It is what is called a trait. The easiest way to understand trait is that it is similar to a Java interface but with key differences; such as it allows you to provide concrete implementations for the methods declared in it, they also allow you to declare fields and maintain state. A class is said to mix in one or more traits and in that respect, Scala provides you a mechanism for multiple inheritance. In the example above we are mixing in another trait called BeforeAndAfter which provides similar functionality as the SetUp and TearDown supported by JUnit. So our test class is a FunSuite with facility to support setup before the test is run and tear down after the test completes execution.
Also notice that we have not written any constructors for our classes (both NumberDispenser as well as its test classes). In Scala one does not have to write a constructor for a class. The compiler generates a primary constructor for a class by collecting all the standalone statements and expression that it finds in the declaration of the body of the class. In this example test class, the standalone statements such as “before” and “test” are actually method calls. These methods are defined in BeforeAndAfter and in FunSuite respectively. The compiler creates a primary constructor for our test class NumberDispenserSuite and puts these method calls in the constructor.
Each “test” statement listed above is a call to the “test” method of FunSuite. The test method takes a string that describes the test as its first argument. Following this string, is a series of code statements in curly braces that might appear to a java developer as a function definition. In reality the code in curly braces is another argument to the test method of FunSuite that uses a technique called “currying”. More on currying will come later for now just know that it enables a developer to create new control abstractions that feel like native language support. In the case of FunSuite, the second argument to the test method is curried and its type is a Function that takes no arguments and does not return anything. This “function value” (and thus the name “FunSuite”), has the actual test code to test our target code. Since all the calls to the test method are part of the primary constructor they are executed when a new object of our class NumberDispenserSuite is created. When these methods execute they register the function value passed as a curried argument to the test method with the Suite class for later execution.
In future blogs we will explore how to use “Behavior Driven Design” using Scala specs and ScalaCheck.
Executing ScalaTest
ScalaTest includes a JUnit Runner that knows how to run any ScalaTest Suite. This enables you to provide a JUnit RunWith annotation on any ScalaTest Suite. Once this is done, you can use Maven to execute the test suite.
Conclusion
In today’s blog we saw how to write a simple Scala class along with its test classes written in JUnit and ScalaTest and JUnit.
The NumberDispenser class is simple. In the next blog we will see an alternate way of generating a stream of numbers using a Scala Collections data structure. Hope you found this blog useful.
