如何重构抛出异常的函数?

How to refactor a function that throws exceptions?

假设我正在重构这样一个函数:

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 _ => ()
}

我想摆脱异常,但我需要保持 check 签名和行为不变,所以我分解出一个纯实现 -- doCheck:

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

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

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

现在我实现doCheck如下:

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

使用以下 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) 
}

有意义吗?

P.S。 implicits肯定会添加更多的代码。我希望有一天用 scalaz/cats 中的 implicit 替换 OptionTry,也许能找到 BoolTry.

的类似物

您可以使用贷款模式和 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"))
}

那么可以如下使用

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)