Why is the second argument to `require()` a functi...
# getting-started
e
Why is the second argument to
require()
a function rather than a string? I can think of two possible answers: 1. In case constructing the message is expensive (seems unlikely). 2. In case we want to do additional processing before throwing the exception, such as logging or cleaning up. I'm teaching about Kotlin exceptions, so I really want to get this right.
c
so it can be lazy and only evaluated when the condition fails
👆 2
🙏 1
j
1. In case constructing the message is expensive (seems unlikely).
Why would that be unllikely? String concatenation with arbitrary
toString()
isn't exactly cheap, so if you're using it in performance-sensitive code, it may be important to not construct the message if it's not used
🙏 1
☝️ 3
k
Don't underestimate the power of lazy evaluation K😆
🙏 1
v
Especially if the syntax is no significant visual overhead like in Kotlin.
require("foo")
vs.
require { "foo" }
🙏 1
e
Thanks, everyone! Is the second answer right too, or is it really only the first?
c
usually just the first. you may wish to do some processing to build the exception message, but shouldn’t be using
require
to alter state, cleanup, etc.
k
You could say that the received lambda in
require
should be a pure function, no side effects
🙏 1
☝️ 1
j
I mean technically it doesn't have to be pure, but it's true that I wouldn't expect side effects there. For anything more complicated than something building a message, or calling a function that builds the message, I would go for a manual
if
statement and throw IAE manually
1
k
Well, that's true theoretically a pure function is more restrictive as it should always return the same value because the lambda doesn't really receive any parameter, but I wanted to take the part of the no side effects
j
Oh sorry I didn't mean to be picky about the "pure" terminology here, and about taking inputs outside the lambda. I was just saying "technically it doesn't have to" in the sense that you could perform side-effects there and it would work. It's just not expected in general.
k
Oh thanks for the clarification, yeah, that's right, there's no contract that forbids you to perform side-effects, but ideally the clean-up and side-effects should be left to the caller of the function after the error, in my opinion, the lambda in
require
should only be concerned to return the error message
j
Agreed. Also I would argue that IAE is a developer/internal error and it is probably not something that should imply cleanup anyway. If there is such error, it's a bug in the code that should be fixed. If there is any cleanup to do, it will probably not be specific to this place, but it will likely be done in a general place that recovers from internal errors
e
Thanks a lot. I've talked about pure functions so can reinforce that here.