これは私の前の質問へのフォローアップです:
次のような関数をリファクタリングしているとします。
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
を返す新しい純粋関数を作成しています。Unit
case class MissingX() extends Exception("X is missing")
case class NegativeX(x: Int) extends Exception(s"$x is negative")
import scalaz._, Scalaz._
type Result[A] = Excepiton \/ A
def doCheck(ox:Option[Int]): Result[Unit] = for {
x <- ox toRightDisjunction MissingX()
_ <- (x >= 0) either(()) or NegativeX(x)
} yield ()
そしてそれを呼び出すcheck
def check(ox:Option[Int]): Unit = doCheck(ox) match {
case -\/(e) => throw e
case _ => ()
}
それは理にかなっていますか?そのように実装した方が良いでしょうdoCheck
か?
def doCheck(ox:Option[Int]): Result[Int] = for {
x1 <- ox toRightDisjunction MissingX()
x2 <- (x1 >= 0) either(x1) or NegativeX(x1)
} yield x2
で実装する方法はcats
?