Which convention is better? 1. ```checkNotNull(x)....
# codingconventions
j
Which convention is better? 1.
Copy code
checkNotNull(x).also {
    // do something like..
    it.prop = y
    // ...
}
2.
Copy code
x?.apply {
    // do something like..
    it.prop = y
    // ...
} ?: throw IllegalStateException()
b
I would favour `requireNotNull`/`checkNotNull` over a safe call and throw here because I think it more clearly and concisely expresses the hard requirement on
x
being non-null. I'd probably go with either
Copy code
requireNotNull(x)
x.prop = y
or
Copy code
requireNotNull(x).apply {
    prop = y
}
depending on whether or not the scoping/return value of
apply
were required in your actual use case.
I tend to reserve
also
for sneaking things with no side-effects like log statements into call chains.
☝️ 2
I prefer
requireNotNull
over
checkNotNull
because I think the name better reflects the consequences but it's worth noting that the exceptions that are thrown are different.
j
Thanks for the opinion. Is a difference between
requireNotNull
and
checkNotNull
(also between
require
and
check
) only something conventional, such that one is used for checking function arguments, and one is used for checking other program states?
b
No problem! I'm not aware of any particular convention to be honest... I guess it's just a matter of which exception type makes the most sense. I haven't used
checkNotNull
but use
requireNotNull
mostly for things like reading from config files or validating POST requests. If my function required a non-null type I would just make that clear in the signature if possible 🙂
o
@Bornyls Deen technically, log statements are side-effects😉.
💯 1