I am just wondering if there is a recommended strategy for dealing with null
candidates in the specification pattern. As I see it, there are two possible strategies:
- Throw an exception if the candidate is
null
. - Return
false
for cases wherenull
is not a valid candidate value.
Examples are written in Kotlin, but this could easily apply to C# and Java as well.
Example - Throw an exception
class RangeSpecification<T : Comparable<T>>(
private val min: T,
private val max: T
) : Specification<T?>() {
override fun isSatisfiedBy(candidate: T?): Boolean {
checkNotNull(candidate)
// ^ Throws IllegalStateException("Required value was null.")
return candidate in min..max
}
}
Example - Return false
class RangeSpecification<T : Comparable<T>>(
private val min: T,
private val max: T
) : Specification<T?>() {
override fun isSatisfiedBy(candidate: T?): Boolean {
return candidate != null && candidate in min..max
}
}
I'm not sure whether this qualifies as an opinionated question (and apologies if that's the case), but I'm just wondering which approach is more suitable in line with the specification pattern?
References