Quick tip: use assertions liberally

Two of the built-in Scala assertions, assume and assert, have a very useful quality: they can be switched off. This means you can sprinkle them pretty liberally throughout your code, switch them off in production, and switch them on during development and testing. This will shorten the feedback loop from bad assumptions or logic, to error message.

Concretely, you can put in the scalac compile flag that switches off assertions into your build:

// build.sbt
scalacOptions ++= Seq(
  ...,
  "-Xdisable-assertions",
)
// build.gradle
tasks.withType(ScalaCompile) {
  scalaCompileOptions.additionalParameters = [
    ...,
    "-Xdisable-assertions",
  ]
}

During local development and testing, comment out this flag and run your app/tests. This will enable the feedback loop that will let you tighten your logic quite a lot. This will happen because callers will be forced to use these functions according to their defined assumptions. Here’s a simple example:

def safeDivide(num: Int, denom: Int): Int = {
  assume(denom != 0, "denom != 0")
  assume(num >= denom, "num >= denom")

  num / denom
}

This will force, by way of runtime exceptions, calling code to ensure that it doesn’t pass in a zero denominator or a smaller numerator.

You may of course recognize this as nothing but a simple form of Design by contract. This is true and I wanted to point out this simple built-in way to get an extra feedback loop for your code logic during development–and which will get erased out from your production code.

2 Likes