以前的答案很好,但我知道您来自 OOP 范式,所以让我再举一个例子来比较这两种范式。
常用代码:
val a = "1"
val b = "aaa"
val c = "bbb"
def isAllDigits(x: String) = x forall Character.isDigit
def appendError(x: String, errors: mutable.Buffer[String]) = errors += s"$x is not number"
type Errors = NonEmptyList[String]
// disjunction \/ for fail fast
def toDigitFailFast(x: String): Errors \/ Int = {
if (isAllDigits(x)) {
x.toInt.right
} else {
s"$x is not number".wrapNel.left
}
}
// validation nel (non empty list) for fail slow
def toDigitFS(x: String): ValidationNel[String, Int] = {
if (x forall Character.isDigit) {
x.toInt.successNel
} else {
s"$x is not number".failureNel
}
}
fail fast 命令的代码:
// fail fast imperative programming
println("---\nFail Fast imperative")
val failFastErrors = mutable.Buffer.empty[String]
if(isAllDigits(a)) {
if(isAllDigits(b)) {
if(isAllDigits(c)) {
val total = a.toInt + b.toInt + c.toInt
println(s"Total = ${total}!!")
} else {
appendError(c, failFastErrors)
}
} else {
appendError(b, failFastErrors)
}
} else {
appendError(a, failFastErrors)
}
if(failFastErrors.nonEmpty) {
println("Errors:")
for(error <- failFastErrors) {
println(error)
}
}
快速失败函数的代码(带析取 /):
val resultFunc = for {
x <- toDigitFailFast(a)
y <- toDigitFailFast(b)
z <- toDigitFailFast(c)
} yield (x + y + z)
resultFunc match {
case \/-(total) => println(s"Total = $total")
case -\/(errors) =>
println("Errors:")
errors.foreach(println)
}
快速失败时的输出(仅告诉您第一个错误):
Fail Fast imperative
Errors:
aaa is not number
Fail Fast functional
Errors:
aaa is not number
现在是命令式的失败慢代码:
// fail slow imperative programming
println("---\nFail Slow imperative")
val failSlowErrors = mutable.Buffer.empty[String]
if(!isAllDigits(a)) {
appendError(a, failSlowErrors)
}
if(!isAllDigits(b)) {
appendError(b, failSlowErrors)
}
if(!isAllDigits(c)) {
appendError(c, failSlowErrors)
}
if(failSlowErrors.isEmpty) {
val total = a.toInt + b.toInt + c.toInt
println(s"Total = ${total}!!")
} else {
println("Errors:")
for(error <- failSlowErrors) {
println(error)
}
}
以及功能版(失败慢):
// fail slow functional programming
println("---\nFail Slow functional")
val resultFuncSlow =
(toDigitFS(a) |@| toDigitFS(b) |@| toDigitFS(c)) { _ + _ + _ }
resultFuncSlow match {
case Success(result) => println(result)
case Failure(errors) =>
println("Errors:")
errors.foreach(println)
}
和两个错误的输出:
Fail Slow imperative
Errors:
aaa is not number
bbb is not number
---
Fail Slow functional
Errors:
aaa is not number
bbb is not number