A tip for when TDD gets hard

One of the biggest reasons I see for TDD not being used enough is that it makes things harder. The typical complaints are:

  • “I have to setup/mock too much”
  • “I want to test my complicated internals without exposing them”
  • “I’m writing a web-app, it’s hard to get the interactions right”

All of these should be alarm bells in your head. The design needs a rethink. These alarm bells are one of the benefits of TDD – if it’s getting tough then the design probably needs a rethink.

Too much setup/mocking

This likely indicates that your classes are too coupled. Consider the following:

  • Is there any functionality that is in the wrong place? Should it be moved to a different/new class?
  • Should you create a simple class with little logic that provides the glue for your application?
  • Have you considered inversion of control?

Testing Complicated Internals

Sometimes you start with something simple and then it gets more complicated. As it gets more complicated the internals get more complex and you start wanting to test the internals to make sure your state is correct. Don’t.

Instead, consider whether those internals could be extracted out in to a new class which has the sole purpose of implementing the complex logic you were trying to hide away.

This makes testing easier, improves re-usability and leads to code that is easier to understand.

Testing Web-apps

Testing web-apps can require a different set of tools. Often, you want to be using some sort of browser based testing as well as your normal testing. Most of your browser based testing should be simple (little logic) and be something of a formality.

If you have all your business logic tidied away nicely in to your models then your views and their controllers should be simple. Your tests for these should then be simple.

You should be able to directly call methods on your controllers to test any logic present in them. If you can’t, then it is likely there is logic in the wrong place or you are storing too much state.

To summarise…

If TDD gets hard – check your design

Presentations and History

Four-year-old child: What’s ice hockey?
Dad: Ice hockey may have started out as a form of hurling that was played on the ice. An account by Thomas Chandler Haliburton suggests that it was played as early as 1810…

Would you really respond like that to your child?

Or would you show them the game?

I’ve seen many presentations that start with a history section. Every single one could have skipped the history and been a better presentation for it.

We don’t want to know the history. Get to the interesting part. Hook us with that and we may want to know the history later.

Show us the game.

Rewriting Java in Scala & Making Code Lovely 6 – Pattern Matching

Pattern Matching – The Problem

I’m going to start off with a code snippet:

if (x instanceof SomeObject) {
  ((SomeObject)x).someMethod();
} else if (x instanceof SomeOtherObject) {
  ((SomeOtherObject)x).someOtherMethod();
}

Eugh. This is ugly. Not only that, it’s something we all see quite often when writing Java. No matter how well we’ve designed our APIs to avoid needing this sort of thing, it always creeps in somewhere.

Scala gives us a (huge) feature called Pattern Matching that allows us to tidy this up:

x match {
  case y : SomeObject => y.someMethod()
  case y : SomeOtherObject => y.someOtherMethod()
}

This is very similar to Java’s switch. The first case clause can be thought of as “if x is of type SomeObject then create a new variable, y, and set it to x”. Unlike some languages, Scala does not have fall through, if the first clause is matched then no other clauses are checked.

I prefer this to Java’s style of doing things because the cast/instance checking is done only once in your code. This is much more readable. Readability is only the tip of the iceberg. Pattern matching is very powerful and I’m now going to cover a few more uses of pattern matching.

Matching Constants

We can match against constants:

x match {
  case 1 => println("ONE!")
  case 2 => println("Two...")
  case _ => println("I can't count higher :(")
}

The first two cases here should be simple to follow. The third one is the same as Java’s default when using switch.

We can also return values out of a pattern match:

y = x match {
  case "one" => 1
  case "two" => 2
  case _ => 3
}

Oh, we can match against strings too… or, if we really want, we can match both in the same match:

x match {
  case 1 => 1
  case "one" => 1
  case _ => 2
}

Matching Regular Expressions

Scala also allows us to match against regular expressions.

val timeformat = """(\d\d):(\d\d)""".r
val time = "19:21"
time match {
  case timeformat(h, m) => println("It is " + m + " minutes past hour " + h)
  case _ => println("You gave me junk :(")
}

Read that again.

In the above example, we create a regular expression that matches times that look like “15:49″, i.e. the standard western way of doing 24 hour times. We then pattern match on the string “19:21″. The first clause will:

  • Check if the given string matches the regular expression
  • If a match is found, the two groups in the regular expression are substituted into variables h and m respectively

You can also ignore parts of the match using placeholder syntax (the underscore) if you want:

val timeformat = """(\d\d):(\d\d)""".r
val time = "4:21"
time match {
  case timeformat(h, _) => println("It is " + h + " o'clock")
  case _ => println("You gave me junk :(")
}

Short and readable. Nice.

Matching Types

Matching types can make equals method remarkably tidy. Suppose we’re writing the equals method for ThisClass which has a single field called someField:

def equals(other : Any) =
  other match {
    case other : ThisClass => other.someField == this.someField
    case _ => false
  }

Easy. The first clause says that if other is of type ThisClass then cast it to ThisClass and put it in a new variable called other (we can re-use the same name here without a conflict). We can then use other to compare the fields. The second clause is the result if no match was found in the first clause (i.e. if other is not an instance of ThisClass).

Matching Anything

In Scala you can use something called an extractor object to match against anything you could ever want. I’m not going to go into this in this post as it’s a big topic that deserves its own posting.

Summary

Many people compare pattern matching to “switch on steroids” or similar. This isn’t an exaggeration. It’s an extremely powerful tool and can lead to very succinct code (especially when doing things with regular expressions).

Rewriting Java in Scala & Making Code Lovely 5 – Structural Typing

What is structural typing?

Structural typing is a way of saying that we don’t care about the type of a variable but we do care about the structure of the type of a variable.

Here’s a simple example to explain this further:

def printArea(shape : { def area : Double}) {
    println(shape + " has area " + shape.area)
}

The interesting part of the above function is the type of the argument shape; shape is a structurally typed variable. We can pass any object we want to the printArea function so long as it has a function called area that returns a Double:

case class square(val sideLength : Double) {
  def area = sideLength * sideLength
}
 
printArea(square(5.0))
// square(5.0) has area 25.0
 
case class circle(val radius : Double) {
  def area = scala.math.Pi * radius * radius
}
 
printArea(circle(10.0))
// circle(10.0) has area 314.1592653589793

We can go as far as you want with specifying structural types:

def pointlessFunction(thing : { 
    def areaWithMultiplier(multiplier : Double) : Double
    def length : Double}) = {
  // ...
}

The above function takes any type that has two functions:

  • areaWithMultiplier that has one argument of type Double and returns a Double
  • length that returns a double

But, the above example is ugly. Type aliases to the rescue:

type t = {
  def areaWithMultiplier(multiplier : Double) : Double
  def length : Double
}
def pointlessFunction(thing : t) = {
  // ...
}

Here we’ve created a type alias t that aliases the complex structural type. We then use that type in the definition of pointlessFunction in the same way we’d use any other type.

What’s the use?

Very Reusable Functions

One of the great uses of structural types is that they allow us to create very reusable functions. For example, we could write a function that sorts a list of shapes according to their size without requiring that the shapes implement a common interface:

type hasArea = { def area : Double }
 
def sortShapes(list : List[hasArea]) : List[hasArea] = {
  list.sortWith(_.area < _.area)
}
 
sortShapes(
  List[hasArea](square(5.0), square(6.0), circle(2.0), circle(3.0))
)
// Result is: List(circle(2.0), square(5.0), circle(3.0), square(6.0))

We could then pass anything we wanted to this function: shapes, countries, building plans, anything with an area function.

This becomes incredibly useful when implementing algorithms. For example, an algorithm that determines how to fit different shapes into a box could be used on any type that implemented the required method.

Legacy Classes

Structural types are also a great way to make legacy types easier to use.

We are given two classes that represent different types of customers: BusinessCustomer, IndividualCustomer. Both of these classes have a method getPhoneNumber. They don’t share a base class. We want to use a library that allows us to call these people from our computer. The typical Java approach might be something like:

public void dial(Object customer) {
  String phoneNumber;  
  if (customer instanceof BusinessCustomer) {
    phoneNumber = ((BusinessCustomer)customer).getPhoneNumber();
  } else if (customer instanceof IndividualCustomer) {
    phoneNumber = ((IndividualCustomer)customer).getPhoneNumber();
  } else {
    throw IllegalArgumentException("Argument isn't a customter " + customer);
  }
  Dialer.dial(phoneNumber);
}

Ugh.

Apart from this being a lot of code for something simple, you won’t be told of errors at compilation time!

Enter structural typing:

def dial(customer : { def getPhoneNumber : String }) = {
  Dialer.dial(customer.getPhoneNumber)
}

Much better. Compile-time safe and far easier to follow.

Duck-Typing

Structural typing is effectively duck typing. Forget littering all your classes with random interfaces IsCloneable, IsSortable, IsComparable, IsJedi… use structural typing and we can say “so long as this argument has a certain property then I’ll use it”.

This gives us some of the benefits of dynamic typing (being able to use whatever we want wherever we want) without losing the benefits of a compiler to make sure we’ve not done something silly.

Under the Covers

Under the covers Scala generates byte-code similar to the following Java:

public void printArea(Object shape) {
    double area = (Double)shape.getClass().getMethod("area").invoke(shape);
    System.out.println("Shape " + shape + " has area " + area);
}

That’s reflection at work. The up-side of this is that we can use our functions from Java code – but without any compile-time type safety. All structural types get compiled down to Object and Scala does the work at run-time to determine if the argument fits the function.

Summary

Structural typing allows us to use arguments according to what properties they have, not what type they are. This can be a very powerful tool and lead to very neat code. It also gives us the benefit of greater compile-time checking when compared against using instanceof in lots of places.

If you want to see a great real-world example of structural typing then take a look at Java to Scala – Smaller Inheritance hierarchies with Structural Typing.

Rewriting Java in Scala & Making Code Lovely 4 – Example: Integration

It’s time for a full example that shows off what we know so far.

For the example, we’re going to implement something that does basic integration. This program will approximate the value of an integral using the rectangle method – a good explanation of this can be found here.

Background

Skip this if you already know what integration and the rectangle method are.

Put simply, integration is finding the area under the graph for a particular function. The article here has more details on this.

The rectangle method is a way of approximating this. The graph for the function is divided into sections. Each section then has a rectangle put in it. The height of the rectangle is the same as the value of the graph at the middle of the section:


Thick rectangles under a graph

This isn’t perfect. All the places where the rectangles are too small or too big are errors in the approximation. These errors can be reduced by dividing the graph in to more sections:

Thin rectangles under a graph

For the purposes of this posting, that’s all there is to it.

The Problem

Make a class that when given a function and a range will approximate the area under the graph. The class can be given the number of rectangles to use.

Java Version

We’ll start off with a Java version of this and then rewrite it to Scala.

public class RectangleMethod {
  public double integrate(double start, double end, int steps) {
    final double stepSize = (end - start) / steps;
    double value = 0; // running total for the area
 
    for (int i = 0; i < steps; i++) {
      // Evaluate the function at the mid-point of the current section
      // The code below could be shorter - but it has been kept purposefully simple
      final double startX = start + stepSize * i;
      final double endX = start + stepSize * (i + 1);
      final double midX = (startX + endX) / 2;
      final double y = function(midX);
 
      // Add on the area of the rectangle for the current section: width * height
      value += stepSize * y;
    }
 
    return value;
  }
 
  private double function(double x) {
    return 20 - Math.pow(x - 4, 2);
  }
}

The Java example above contains a hard-coded function: 20 – (x – 4) * (x – 4).

That’s not quite the solution to the problem. We must be able to provide a function to this method so that we can do integrations for any function. We can do this by making the integrate method take an interface and then the caller must implement this interface for any function it wants to integrate:

public class RectangleMethod {
  public double integrate(Function function, double start, double end, int steps) {
    final double stepSize = (end - start) / steps;
    double value = 0;
 
    for (int i = 0; i < steps; i++) {
      final double startX = start + stepSize * i;
      final double endX = start + stepSize * (i + 1);
      final double midX = (startX + endX) / 2;
      final double y = function.y(midX); // Call the function passed in
 
      value += stepSize * y;
    }
 
    return value;
  }
 
  // New interface for arbitrary functions
  public interface Function {
    public double y(double x);
  }
}

I’ve commented the parts that have changed and removed the old comments.

This now lets us pass in any function we want:

double value = new RectangleMethod().integrate(new Function() {
  public double y(double x) {
    return 20 - Math.pow(x - 4, 2);
  }
}, 0, 1, 200);

This will approximate the integral of 20 – (x – 4) * (x – 4) between 0 and 1 with 200 sections. This requires a lot of work to define a function every time you want to integrate it.

Scala – Simple Version

Now lets take our Scala knowledge so far and convert the above code. We’ll start with the simple Java version:

class RectangleMethod {
  def integrate(start : Double, end : Double, steps : Int) = {
    val stepSize = (end - start) / steps // width of each step
    var value = 0.0 // running total for the area
 
    for (i <- 0 until steps) {
      // Evaluate the function at the mid-point of the current section
      // The code below could be shorter - but it has been kept purposefully simple
      val startX = start + stepSize * i
      val endX = start + stepSize * (i + 1)
      val midX = (startX + endX) / 2
      val y = function(midX)
 
      // Add on the area of the rectangle for the current section: width * height
      value = value + stepSize * y
    }
 
    value // Scala doesn't need the return keyword here
  }
 
  def function(x : Double) = {
    20 - Math.pow(x - 4, 2)
  }
}

For loops

I’ve slipped something new in to the example above, the for loop. In Scala there are many ways to write a for loop, this is one of them. The for loop above will iterate i over the values 0 to steps and exclude steps. E.g.

for (i <- 0 until 10) print(i)

Will print 0123456789. To make it include the final value change until to “to”:

for (i <- 0 to 10) print(i)

Will print 012345678910.

There are more ways to define for loops and I’ll come back to them in later posts.

Scala – Better Version

Now we use our knowledge of using functions as arguments to pass a function to the integrate method:

class RectangleMethod {
  def integrate(
      function : Double => Double, // Add the function argument on
      start : Double, end : Double, steps : Int) = {
    val stepSize = (end - start) / steps
    var value = 0.0
 
    for (i <- 0 until steps) {
      val startX = start + stepSize * i
      val endX = start + stepSize * (i + 1)
      val midX = (startX + endX) / 2
      val y = function(midX) // No need to change this!
 
      value = value + stepSize * y
    }
 
    value
  }
}

We’ve added a single argument to the integrate function. The argument is a function that takes a Double as a parameter and returns a Double. To use this new method:

new RectangleMethod().integrate(
  x => 20 - Math.pow(x - 4, 2), 
  0, 1, 200)

I hope that you’ll agree that using this new version is much neater than the Java example.

Scala – Tiny Version

We can make the integrate method really compact and neat.

The first step is to merge the mid-point calculation:

val startX = start + stepSize * i
val endX = start + stepSize * (i + 1)
val midX = (startX + endX) / 2
// Becomes (by substitution and simplification)...
val midX = start + stepSize * i + stepSize * 0.5)

Then simply the calculation of y

val midX = start + stepSize * i + stepSize * 0.5)
val y = function(midX)
// Becomes...
val y = function(start + stepSize * i + stepSize * 0.5))

And finally, move y into the running total calculation:

value = value + stepSize * function(start + stepSize * i + stepSize * 0.5))

This leaves us with:

class RectangleMethod {
  def integrate(
      function : Double => Double, 
      start : Double, end : Double, steps : Int) = {
    val stepSize = (end - start) / steps
    var value = 0.0
 
    for (i <- 0 until steps) {
      value = value + stepSize * function(start + stepSize * i + stepSize * 0.5))
    }
 
    value
  }
}

Whenever you see this pattern in Scala you should be thinking about whether it can be turned in to a call to foldLeft. The things to look for are:

  • A collection to fold over – in this case (0 until steps) is actually a collection (I’ll cover this more in later posts)
  • A running total – in this case value is a running total

Now we use foldLeft to make this more compact:

class RectangleMethod {
  // Add the function argument on
  def integrate(
      function : Double => Double, 
      start : Double, end : Double, steps : Int) = {
    val stepSize = (end - start) / steps
    (0 until steps).foldLeft(0.0)((runningTotal, i) =>
      runningTotal + stepSize * function(start + stepSize * i + stepSize * 0.5))
  }
}

And, that’s it.

There are many other ways to rewrite this, and I would love for you to come up with your own and leave it here as a comment :)

Rewriting Java in Scala & Making Code Lovely 3 – Variable Declarations

I thought I’d take a step back and look at how variables are declared in Scala and how it compares with Java.

Local Variables

In Java you declare a local variable like this:

Map<String, Integer> userIds = new HashMap<String, Integer>();

In Scala, it is a lot shorter:

var userIds = new HashMap[String, Integer]

The type of the variable is missing. This is because Scala can calculate the type. In this case it will calculate that userIds is of type HashMap[String, Integer]. The Scala site has more information on how it calculates the types (this is called type inference).

Another minor detail here is that you use square brackets [ ] instead of angle brackets < > to specify generics.

Constants

In the above example we declared userIds with the keyword ‘var’. This makes it a variable – we can change userIds to point at a different HashMap if we want.

In Java we can say that a variable is constant using the final keyword:

final int x = 4;
x = 5; // Compile error: cannot change x

Scala doesn’t have the final keyword when declaring variables. Instead, you use the ‘val’ keyword:

val x = 4
x = 5 // Compile error: cannot change x

This has a benefit that isn’t obvious.

Every time you declare a variable you specify whether you can change it or not.

There are many good reasons to make something constant (or, immutable as many people like to say). However, in Java it is easy to forget to make something immutable, it is also a burden as you have to write more every time you want to keep something constant. In Scala, you make an active choice every time you declare a variable. It is also easy for constants to be the default that you use.

Specifying Types

Sometimes, you may want to specify the type of a variable. This is easy:

val x : Int = 4
val name : String = "Bob"

Normally, you won’t need to do this. Only when you have a specific type requirement or Scala has failed to infer the types – a rare event!

Summary

You’ve now been introduced to variable declarations. Scala improves this basic area of programming in a number of ways:

  • Reduces repetitiveness by not writing types all the time
  • Makes the choice of constant/not constant an active choice
  • Makes it easier to alter types of variables

The next part of this series will follow on from this and take a look at declaring fields in classes.

Rewriting Java in Scala & Making Code Lovely 2 – Functions as values

Ever wanted to filter a collection in Java and thought “this sucks”? Typically, you end up with code like:

List evens = new LinkedList();
for (Integer i : list) {
  if (i % 2 == 0) evens.add(i);
}

Or, if you’re going for re-use:

Predicate evenNumbers = new Predicate() {
  @Override
  public boolean evaluate(Object o) {
    Integer n = (Integer)o; // Assume list contains only integers
    return n % 2 == 0;
  }
};
CollectionUtils.filter(list, evenNumbers);

Which is actually longer.

In Scala, functions can be values and this makes the above examples become very short:

val evens = list.filter(_ % 2 == 0)

You’re not supposed to understand this yet – it’s the bait to get you to read further ;-)

Defining Functions in Scala

Before we focus on this I’m going to quickly show you how functions are defined in Scala:

def getHelloString(username : String) : String = {
  "Hello " + username
}

This defines a function called getHelloString. It takes a single argument of type String called username and returns a String. Unlike Java, the type of an argument goes after the name. Likewise, the return type of a function goes after the argument list. It’s also worth noting that there isn’t a return statement here, the value of the last expression in the function is the return value.

That’s all I’m going to say on functions for now – I’ll come back to them in more detail in a later post.

Functions as Arguments

Let’s take a look at the signature for the method filter:

def filter(p : (A) => Boolean) : Iterable[A]

This method takes an argument p and returns an Iterable[A] (the [A] is how you specify generics in Scala but we can ignore this for now).

The argument p is the interesting bit. The type of p is a function that takes an A (generics again) and returns a Boolean. To help this make sense here are a few more examples:

def a(p : String => Boolean) : Boolean
// The type of p is a function that takes a String and returns a Boolean
 
def b(p : String => List[String]) : Boolean
// The type of p is a function that takes a String and returns a list of strings
 
def c(p : (String, Boolean) => Int) : Boolean
// The type of p is a function that takes a String and a boolean and returns a list of strings

This is very different to Java. In Java you would define an interface and use that as the argument type (just like in the CollectionUtils example above).

Coming back to filter, we now know that it takes a single argument. That argument must be a function which takes a single argument of type A and returns a boolean. What is A? A is the same type as the type of the list we are filtering over. So:

List("A", "B").filter(...)
// requires a function that takes a String and returns a Boolean
 
List(1, 2).filter(...)
// requires a function that takes an Int and returns a Boolean

With the knowledge we have so far we could comfortably write:

def isEven(n : Int) : Boolean = {
  n % 2 == 0
}
 
List(1, 2, 3, 4, 5, 6).filter(isEven)

And we’ll get a list containing only the even numbers.

Function Literals

This is all very well and good, but it’s still a lot to write – especially if we only ever use the isEven function in one place.

Fortunately, Scala offers a short-hand that allows us to write functions in-line:

List(1, 2, 3, 4, 5, 6).filter(n => n % 2 == 0)

The way this is written above is very similar to the argument types above. The argument passed to filter here is known as a function literal.

Placeholder Syntax

Scala gives us one further refinement to this:

List(1, 2, 3, 4, 5, 6).filter(_ % 2 == 0)

On first reading this can be cryptic. It’s called placeholder syntax. The _ is a placeholder for the 1st argument to the function. When Scala sees this it replaces the _ with the 1st argument to the function. Each subsequent _ is a placeholder for the next argument. If we wrote:

dostuff(_ + _)

This would be the same as:

dostuff((a, b) => a + b)

It’s important to note that when writing function literals with the arguments named parentheses must be used to group the arguments. This is to prevent ambiguity:

dostuff(a, b => a + b)

Could be read as:

dostuff(
  a,
  b => a + b)

Which isn’t what we intended.

I learn best by example, so here are a few more examples of function literals.

Further Examples

Map

Map is one of the most useful functions in Scala’s collections:

Map creates a new collection based on the original. Each element in the new collection is the result of applying the function given to each element in the original collection.

List(1, 2, 3, 4).map(_ * 2)
// Returns: List(2, 4, 6, 8)
 
List(1, 2, 3, 4).map(_.toString)
// Returns: List("1", "2", "3", "4")

findIndexOf

Finding the index of an element in a list is also very easy:

List(1, 2, 3, 4).findIndexOf(_ % 2 == 0)
// Finds the index of the first even number, or -1 if no such number exists

Count

How about counting the number of even numbers in a list?

List(1, 2, 3, 4).count(_ % 2 == 0)
// Returns 2
 
List("Hi", "Bye", "Hey", "Goodbye").count(_.length == 2)
// Returns 1

What’s this given us?

More concise, more readable

Goodbye anonymous inner classes. If you’ve ever written something that fires events you’ll know how horrible these can be.

Once I got used to passing functions around as arguments I soon realised how often I can re-use the same basic operations. Map and filter are two of the most used constructs in Java – I love that I can now write them in one line.

Easier to debug

The great thing about using functions as arguments is that you can write an algorithm once, and never again. I don’t want to think about how many times I’ve written a basic loop in Java and forgotten to deal with the last case, off-by-one errors, etc.

Easier to test

Now that I can extract out algorithms more effectively I can test them to hell and back. After that, I only have to test that I’m calling them correctly – I don’t have to retest all the corner cases all over again.

Summary

You should now understand:

  • Functions can be passed as arguments to other functions
  • Functions can be written in-line as literal functions
  • Literal functions can be extremely short when using placeholder syntax

If you don’t, don’t worry! If you’ve not come across functional programming before it can be quite a brain melting experience. My advice is to grab the Scala REPL and put in some of the examples above… then experiment and have fun!

Rewriting Java in Scala & Making Code Lovely 1 – Case Classes

This is the first in a series of posts for people who know Java and are learning Scala. Apart from teaching Scala I hope these posts show how Scala makes your code lovely…

What does more lovely mean?

Lovely covers several things:

  • More concise
  • More readable
  • Easier to debug
  • Easier to test
  • Easier to maintain

I’m not saying Scala is a silver bullet – I’m saying it gives you more time and support to get the hard parts right.

Anyway, on with the show. First up:

Case Classes

Case classes in Scala look something like:

case class Employee(name : String)

They are a short-hand for defining simple classes. They provide you with default implementations of equals, toString and hashCode. They also provide you with some handy tricks when doing pattern matching (which I’ll talk about in a future post).

The great benefit of case classes is that you can take a Java class such as:

class Point {
  private int x;
  private int y;
  public Point(int x, int y) {
    this.x = x;
    this.y = y;
  }
  public String toString() {
    return "Point(x: " + x + ", y: " + y + ")";
  }
  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof Point)) {
      return false;
    }
    Point other = (Point)obj;
    return other.x == x && other.y == y;
  }
  @Override
  public int hashCode() {
    return x * 17 + y;
  }
}

and rewrite as

case class Point(x : Int, y : Int)

That’s it.

No, really, that’s it.

You can provide different implementations of toString, equals and hashCode if you really want to. But the majority of the time the default implementations are spot on.

What’s this given us?

More concise, more readable

It’s a one liner. But, it’s not a Perl one liner ;-)

Easier to debug

There isn’t any functionality here to debug – but the standard toString makes debugging code that uses this class far easier. The default toString will result in something like:

Point(3, 4) 
// The order here is the same as the order in the case class definition

Isn’t this nicer than “Point@0×02345678″ as a default?

Easier to test

There’s nothing to test. It’s reasonable to assume that Scala gets the default toString and equality methods correct – so why test them again?

Easier to maintain

Future maintainers don’t have to look at the toString, equals and hashCode methods when they familiarise themselves with the class. As they don’t exist, they can’t introduce bugs there either!

Summary

Case classes are a great way of defining simple and useful classes with very little code. Goodbye huge files for simple POJOs.

Introducing Gleam

Over the past few months I have been working on a new programming language for the JVM. It’s called Gleam and its purpose is to make view layer programming for web applications easier.

You can read more on the approach taken and the problems it is trying to solve here and here.

I have created a site for Gleam (written using Gleam) and it is located at http://www.gleam-lang.com.

The source for Gleam is on github at http://github.com/gleam. The compiler is written in Scala and is gradually getting completely rewritten now that I’ve firmed up the design (read: I’m not proud of the code itself, just what it does).

So, without any further ado, have a play!

Feedback

I’d love to hear any feedback or questions on this! Please comment, twitter, e-mail me and I’ll get back to you :)

Language Wish-List: Add Information to Exceptions

Following a discussion over on David MacIver’s blog. I have a piece of functionality I’d like to see in more languages.

The ability to easily add information to exceptions

try {
  // ...
} catch (Exception e) {
  e.addInformation("serverName", serverName);
  throw e;
}

Or, even better, a way to annotate variables to get this for free/cheap:

@PutInExceptions String serverName = config.getServerName;

The advantage of being able to add this information is that it makes it easier to diagnose exceptions without losing the type of the exception. Often, when we see an exception we get a full stack trace telling us the line that caused it but not enough surrounding information to make replication easy. Consider the following:

public User getUserDetails(int id) {
  if (!cache.contains(User.class, id)) {
    // Populate the cache
  }
  User user = cache.get(User.class, id);
  log("Got user with name ["+user.getName()+"]");
  return user;
}

If this blows up on the log line then all we know is that user is null. We don’t know the id that was used. This can make debugging harder.

Having the ability to annotate things as “add this to any exception that occurs” makes it easy and cheap to get good error handling. If you then want a method to be ultra-fast then you don’t add the annotations – simple.