Skip to content

Instantly share code, notes, and snippets.

@aurelijusb
Last active January 3, 2016 19:29
Show Gist options
  • Save aurelijusb/8509033 to your computer and use it in GitHub Desktop.
Save aurelijusb/8509033 to your computer and use it in GitHub Desktop.
Scala trait for debugging infinity recursions.

Usage

  • Extend your class with Debugable trait
  • (optional) write initialCommands in build.sbt
  • run sbt REPL on file chage

Extending

See example.scala

initialCommands

For example:

initialCommands in console :=
  """
    |import my.specific.package._
    |MyClass.best(12345)
    |MyClass.best(1.234)
    |MyClass.best(100)
  """.stripMargin

sbt

sbt
~console
trait Debugable {
private final val DEBUG_MAX_I = 800
private var debugI = 0
def d(text: String): Unit = {
println(text)
try {
val stack = Thread.currentThread().getStackTrace()
val element = stack(3)
println(s"\t$element")
} catch {
case e: Exception => println("Something went wrong")
}
debugI += 1
if (debugI > DEBUG_MAX_I) {
throw new InfinityRecursion
}
}
class InfinityRecursion() extends RuntimeException("Infinity recursion")
}
object MyClass extends Debugable {
def smaller(number: Double): Double = {
d("Checking smaller") // for more detailed checking
if (number > 100) smaller(number / 100) else number
}
def larger(number: Double): Double = {
d() // for fast checking
if (number < 100) larger(number * 100) else number
}
def best(number: Double): Double = {
if (number > 100) smaller(number)
else if (number < 100) larger(number)
else {
d("Other case") // Posible source of error
best(number)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment