Tool-friendly Scala code.

What? Why?

People complain a lot about Scala tooling. People complain a lot about weather. But is Scala tooling like weather? Something you can’t do anything about except from moving to different climate (language)? Luckily no.

Scala tooling was created for Java (especially metadata handling that is vital for tools) and usually has only the JVM stack to work with. Tool-friendly code for me is Scala code that make tools’ lives easier.

I’m not trying to convince anyone to write java-like code. I just want to to point out some small details that can make your code much more tool-friendly. In forthcoming blog posts I will show a few codestyle ideas that will make your code easier to debug, profile and — surprisingly — understand. Let’s start with pattern matching.

Tool-friendly pattern matching

Pattern matching is one of the features we love in Scala. Is it tool-friendly?

Let’s look at a standard pattern match snippet:

Let’s see how the first case statement is compiled into byte code:

There is a lot going on in the single line. Let’s assume that we want to check if our case is hit and we put a breakpoint on the case line. What happens? It is hit every time the condition is being checked!

Why? Checking a condition is also in our line, so tooling gets the information: “I was there”.

How would tools like to see the code?

The only difference is line breaking, but this isn’t python so why does it matter? Tools like code coverage or debuggers usually use JDI, which is line-based: every line of the bytecode has its mapping to a line in the source code.

Conclusion

Let’s write cases this way:

Then, when we place breakpoint inside a case body, it will be hit only when the body is about to be invoked.