Are there any articles/guides on best practices wh...
# spring
a
Are there any articles/guides on best practices when validating input objects in Spring Boot? Let's say we have a data class like this:
Copy code
data class MyInput(val foo: Foo?, val bar: Bar?)
How do we validate that one of these are non null? What is the best practice? Is it:
Copy code
requireNotNull(input.foo) { "field foo cannot be null" }
Or is it something like:
Copy code
val foo = input.foo ?: throw SomeException("...")
What is the most idiomatic way?
t
I would probably look at validation frameworks, there are many and I find them nice because they give you consistency in how you collect and present errors. my favorite one is still hibernate-validator (https://hibernate.org/validator/) since it is the reference implementation for the jakarta validation standard (but it's quite heavy and probably not very popular among kotlin in general since it heavily relies on annotations) I thought there was a kotlin wrapper for hibernate validator but atm I cannot find the github project, so I might be misremembering
a
Interesting point, do you have experience with https://github.com/konform-kt/konform say?
t
no, I just glanced at it a while ago but in the end stuck with hibernate stuff. there are several articles suggesting it though
k
If
foo
has to be non-null to be valid, you could simply make it non-nullable:
Copy code
data class MyInput(val foo: Foo, val bar: Bar?)
and if you try to deserialize a null JSON from an HTTP request, it will respond with an error (usually just where you want it)
k
not sure how is it now, but in the past working with parsing exceptions was pain
on the other hand passing string where number is expected is I guess on the same level as passing null in not null attribute
so one thing is schema validation and other is some business validation
t
that is a good point, schema validation is a bit annoying because of the binding exceptions, you could use some json schema and an interceptor on the "raw" request for that, but it's probably overkilling in most situations and a bit complex. otoh, (side note), in our services we use PATCH rather than PUT and that is annoying too, because fields that are mandatory when you create a resource are by definition optional in a PATCH, so in the end we do have endpoints getting plain strings anyway. I guess what I mean is that is depends on your actual use case
for business validation I would definitely used something more structured, hibernate, konform, anything else honestly, so that you get a consistent error that you can format and expose via API more easily (thinking of spring problem details here, it's for sure easier to map a consistent input than custom errors)
a
@Klitos Kyriacou wish it was that easy 😛
foo
is sometimes null, but other times it cannot be. So the validation needs to be a bit more complex.