이러한 모호성을 명시적으로 피하려면 적합한 오류를 발생시켜 좀 더 유익하고 투명하게 함수를 수정해야 한다. 이 문제를 해결하려면 벡터 길이가 1인지 여부만 확인하면 된다.
> calc <- function(x, y, type) { + if (length(type) > 1L) stop("Only a single type is accepted") + if (type == "add") { + x + y + } else if (type == "minus") { + x - y + } else if (type == "multiply") { + x * y + } else if (type == "divide") { + x / y + } else { + stop("Unknown type of operation") + } + }
그런 다음 앞에서 문제가 되었던 코드를 다시 돌려 보자. 인수를 미리 확인하여 예외 처리되는 것을 확인할 수 있다.
> calc(1, 2, c("add", "minus"))
Error in calc(1, 2, c("add", "minus")) : Only a single type is accepted