So, I recently added some validation logic to our controllers:
interface Validator<T> {
fun validate(model: T): Boolean
}
Which is used in the controller like this:
validator.validate(request) || throw Exception()
During code review my colleague was thrown off by validate || throw
construct, while to me it is succinct and communicates intent very clearly. I think it is similar to a expression ?: action
construct, only it acts on a boolean false instead of a null.
Does this seem clear to you? If no, how would you refactor it?
||
for control flow like this is a bit iffy, so it's understandable that some people don't like it. The alternative is anif
statement, though this requires the condition to be negated. Another alternative is to throw the exception from within the validator function, which tends to be safer and can sometimes lead to better error messages. – amon Mar 29 '24 at 08:33validate ||
would have stayed the same. How can I rephrase my question to become fact based? Isn't this type of question opiniated by definition? – Dennis Haarbrink Mar 29 '24 at 13:33if x throw new
idiom that don't work well precisely because theynew
in weird places. That can foul up the stack trace and remove the original context. I actually don't see why you can't do a normalnew
on the same line as the||
. – candied_orange Mar 29 '24 at 20:46new
at all. – Dennis Haarbrink Mar 30 '24 at 06:30