match expression nested inside a case body of another match
ID |
scala.maintainability.nested_match |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Complexity |
Language |
Scala |
Rationale
Nesting multiplies the number of paths through the code: the reader has to track the outer pattern that is already bound while working out which inner arm applies, and each combination needs its own test. Scala can usually express the same decision as one flat match over a tuple or a richer pattern, which is both shorter and checked for exhaustiveness by the compiler.
The following code illustrates the pattern detected by this rule:
class NestedMatch {
def describe(a: Option[Int], b: Option[Int]): String = {
// FLAGGED: match expression nested inside a case body of another match
a match {
case Some(x) =>
b match {
case Some(y) => s"both $x and $y"
case None => s"only $x"
}
case None => "neither"
}
}
}