Is it better to write this initialization logic in...
# codingconventions
f
Is it better to write this initialization logic into an
init
block or directly on the property?
Copy code
val name: String = if (name.isBlank()) "No Name" else name.trim()
vs
Copy code
init {
    if (name.isBlank()) {
        this.name = "No Name"
    } else {
        this.name = name.trim()
    }
}
1️⃣ 12
s
val name = name.takeIf { isNotBlank() }?.trim() ?: “No Name”
m
You will definitely not pass a code review with me, trying to get the above into master 😂
💯 3
f
@Matteo Mirk Are you referring to me or @sikri?
s
To me, of course, guys cannot handle the =CoOl CoDe=
m
Yes @Florian, I was referring to @sikri snippet. To me, that is very cool for code golf, but not suitable for production code, which needs to be maintained by many devs 😉
f
Thank you for the clarification
I can't find many valid examples for init blocks that don't throw an exception
I can only find examples that are better of directly on the property
like
Copy code
val name: String

init {
    name = "Hans"
}
c
I think the first line makes more sense. I usually reserve the
init
block for situations when the entire class has some setup that takes place (such a a custom view with Android), if it’s just setting up the property then I think it’s better for that to live at it’s definition.
f
Thanks Cody 👍
but transforming the input like I do it here is generally not good convention, is it?
Should it throw an exception instead if the name is not valid?
m
Yes you should: you don’t want an invalid object to be constructed, a class guarantees validity and invariants consistency of the type it’s representing, so it should definitely throw on invalid input