Search code examples
scalaexceptionrefactoring

How to refactor a function that throws exceptions?


Suppose I am refactoring a function like this:

def check(ox: Option[Int]): Unit = ox match {
  case None => throw new Exception("X is missing")
  case Some(x) if x < 0 => throw new Exception("X is negative")
  case _ => ()
}

I'd like to get rid of the exceptions but I need to keep the check signature and behavior as is, so I'm factoring out a pure implementation -- doCheck:

import scala.util.{Try, Success, Failure}

def doCheck(ox: Option[Int]): Try[Unit] = ???

def check(ox: Option[Int]): Unit = doCheck(ox).get

Now I am implementing doCheck as follows:

def doCheck(ox: Option[Int]): Try[Unit] = for {
  x <- ox toTry MissingX()
  _ <- (x > 0) toTry NegativeX(x)
} yield ()

Using the following implicits:

implicit class OptionTry[T](o: Option[T]) { 
  def toTry(e: Exception): Try[T] = o match {
    case Some(t) => Success(t)
    case None    => Failure(e)
  }
}

implicit class BoolTry(bool: Boolean) { 
  def toTry(e: Exception): Try[Unit] = if (bool) Success(Unit) else Failure(e) 
}

The implicits certainly add more code. I hope to replace OptionTry with an implicit from scalaz/cats someday and maybe find an analog for BoolTry.


Solution

  • You could refactor with a loan pattern and Try.

    def withChecked[T](i: Option[Int])(f: Int => T): Try[T] = i match {
      case None => Failure(new java.util.NoSuchElementException())
      case Some(p) if p >= 0 => Success(p).map(f)
      case _ => Failure(
        new IllegalArgumentException(s"negative integer: $i"))
    }
    

    Then it can be used as following.

    val res1: Try[String] = withChecked(None)(_.toString)
    // res1 == Failure(NoSuchElement)
    
    val res2: Try[Int] = withChecked(Some(-1))(identity)
    // res2 == Failure(IllegalArgumentException)
    
    def foo(id: Int): MyType = ???
    val res3: Try[MyType] = withChecked(Some(2)) { id => foo(id) }
    // res3 == Success(MyType)