anyway to add some validation to the primary const...
# announcements
v
anyway to add some validation to the primary constructor of a data class? For example I don’t ever want the first parameter to be a negative number
r
Some ideas • Use unsigned numbers (if it's an integral type) • Throw an exception in the
init
block • Use a helper function with a nullable/result wrapper return
v
ugh, forgot about init, I think that will do it. Thanks!
👍 1
t
you could use a validation library, though that would validate after the object is constructed and not during construction. you get some additional feature, like consistent error validation, 0 code etc. I like javax validation (main implementation is hibernate validator), but heard good things about konform if you want to stay kotlin only (more code seems to be required with konform, hibernate is pure annotation for simple cases like negative numbers)
s
Try not to throw exceptions in constructors. In Kotlin, you can use so-called smart constructors (through the use of the operator-function
invoke
on a class' companion object):
Copy code
class MyClass {
    ...
    companion object {
        operator fun invoke(value: Int, ..., ...): MyClass? { 
            if (value < 0) return null // return null instead of throwing exception
            ... 
            return myClass
        }
    } 
}
k
why not to throw exceptions? if you want to guarantee correct state of the object?
s
Why an exception? Why not return
null
or an
Optional<MyClass>
with the value
None
or an
Either.Left
value if input validation fails? 😀 Smart-constructors (basically a factory that looks like a constructor when you call it) allow you to do this.
k
I guess I am old school 🙂, but in my experience more often then not there is nothing much to do with this inconsistent state, so why force caller to handle that
s
😀 I'm a bit biased against exceptions. 😀 They are good for external services (resource issues, corrupt data, bad connections, etc) and for truly exceptional circumstances (memory issues, linking/jvm-validation issues, etc). I like a more functional approach in business models and business logic, where functions are pure and complete, ie never throw an exception.