Friday, May 8, 2020

Compiler settings for bug hunting


Here's a subtle bug that tripped me up this week.

Take this innocuous ZIO test code:

  override def spec: ZSpec[TestEnvironment, Any] = suite("Look closely....")(
    testM("Why is an obviously wrong assertion passing?") {
      ZIO("Actual").map { x =>
        assert(x)(equalTo("Actual")) &&
          assert(x.toUpperCase)(equalTo("ACTUAL")) &&
          assert(x)(equalTo("Obviously wrong")) &&
          assert(x.length)(equalTo(6))
          assert(x.toLowerCase)(equalTo("actual"))
      }
    }
  )

The test should fail as x is clearly not "Obviously wrong". I wasted an hour wondering whether I really understood the ZIO effect system at all. 

Then I saw the missing  && d'oh. 

What can you do to mitigate such errors? This is one kind of bug that wouldn't happen (or would at least be obvious) in Python where whitespace is significant. Wouldn't it be good if the compiler caught this?

Well, you can get the compiler to emit very loud warnings by using the warn-value-discard flag. You can make the compilation fail with -Werror or -Xfatal-warnings (see here). And you can fine tune the warnings with Scala 2.13.2 (see here).


No comments:

Post a Comment