如何重构引发异常的函数? [英] 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 _ => ()
}
我想摆脱例外,但我需要保持检查
签名和行为是一样的,所以我正在考虑一个纯实现 - doCheck
:
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
现在我正在执行 doCheck
,如下所示:
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 ()
使用以下 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)
}
有意义吗?
PS implicits
肯定添加更多的代码。我希望从 scalaz / cats
OptionTry 替换隐式
>有一天,也许找到一个模拟的 BoolTry
。
P.S. 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
.
推荐答案
你可以
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"))
}
然后可以使用如下。
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)
这篇关于如何重构引发异常的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文