12 January 2012

Generating bytecode with errors in Scala


Following this blog post from James Iry: Type errors as warnings, and as it's something I've been thinking about recently applying to the Scala-IDE (Eclipse plugin for Scala),
I thought I'd stick my oar in as well.

The Eclipse JDT compiler creates the .class file even when there are errors in the source code. For instance:
public class Foo {
public void error() {
int foo = "bar";
}

public void ok() {
int foo = 4;
}
}
If you take the above java as an example, the javac compiler would not generate the .class file, but the Eclipse JDT compiler does.
It produces the equivalent of the following (using JAD):
public class Foo {
public Foo() {}

public void error() {
throw new Error("Unresolved compilation problem: \n" +
"\tType mismatch: cannot convert from String to int\n");
}

public void ok() {
int foo = 4;
}
}
Note that this still shows up as a compilation error in Eclipse, in the Problems view. Note also that calling the error() method will never work.

So should we apply the same trick to Scala? Yes.

But why is this useful? When you're refactoring, or just plain developing, you don't have to fix all of your errors at once.
If you're doing a spike, you can do a single change, make sure it works by running the unit tests (for that class), and then move on to the next implementation.
You can experiment. You can see if a solution works.

Note that I am not suggesting relaxing any type constraints, or any constraints of any kind.
Note also that I've never seen problems come from this feature of Eclipse either; actually, I've never worked on a project where the Eclipse
compiler was used for producing production code. It's always been javac.
I'm also not suggesting that this be available with the normal scalac compiler.
I think it should only be available from the Eclipse IDE, to stop leakage into production code.

20 November 2011

Central exception handling in Scala

Have you ever seen this in Java code?
public class AssignResponseImpl extends ServletSupport {
public AssignResponse assign(Ident ident, int low) {
try {
return getService().assign(ident, low);
} catch (Exception e) {
logger.debug("caught Exception", e);
return new AssignResponse("ERROR", e.getMessage());
}
}
}
This sort of java code always irritates me. I've got about 20 of these classes. They are there to glue the Axis servlets to my services.
The reason I don't like them is you can't factor them. And because you can't factor them, it's difficult to create (and maintain) standard behaviour.
Like always logging the error. And always returning the exception message in the correct place. Let's have a look at another:
public SearchResponse search(Ident ident, Criteria criteria) {
try {
return getService().search(ident, criteria);
} catch (Exception e) {
logger.debug(e);
return new SearchResponse("ERROR", e.getMessage());
}
}
Notice the subtle change in behaviour? No? It's in the logger. These methods are in two different unrelated services. But they are very similar, and require the
same error handling.
Now, SearchResponse and AssignResponse share a common superclass, Response. So in the case of an exception, only the class differs, the fields
we're filling in are those in Response. This doesn't really help in Java, we have to cut and paste the try catch, with only the name of the class changing.
We also have to add
in the extra constructor into the subclasses, and all they do is fill in the fields in the superclass. But in Scala, we can use
two tricks: manifests and first class functions.


Manifests allow you access to information about classes which you wouldn't normally have available in Java, in this case the
return type of the service method (A):
abstract class ServletSupport[A <: Response] {
protected def exception(fn: => A)(implicit m: Manifest[A]): A = {
try {
fn
} catch {
case e => {
logger.debug("caught Exception", e)
// create new instance of A
val t = m.erasure.newInstance().asInstanceOf[A]
t.setResponseCode("ERROR")
t.setMessage(e.getLocalizedMessage())
t
}
}
}
}
In our service endpoint superclass, we've defined exception, which takes as parameters a function (taking no parameters and returning
A, the return type of our target method), and an implicit Manifest parameter. Importantly, this is added by the Scala compiler, so we don't have to add
the parameter manually.
In this case, we're asking for extra information about A.


Our exception method calls the passed in function, and if there isn't an exception thrown, then it returns the value returned by the function. If there is
an exception, then the return value is a new instance of A, with the response code and message filled in. We know that we can call setResponseCode and setMessage on an A
because in the class definition, we're setting the type bounds of A, it has to extend Response. OK, so what is our calling code like now?
class AssignResponseImpl extends ServletSupport[AssignResponse] {
def assign(ident: Ident, low: Int) = exception {
getService().assign(ident, low)
}
}
Now, we have standard error handling between web services; all I have to do is add a exception {} round the delegated call. In this case, we can use {} rather than ():
this means it looks like it's part of the language. And this is all type safe, I only have to specify the name of the response class once in the definition.