any thoughts on this pattern to attempt to log the...
# announcements
any thoughts on this pattern to attempt to log the specific reason a chained boolean expression failed without having to have separate branches. (example is a bit contrived, just curious about thoughts on the pattern, or if there’s a better approach)
Copy code
fun Boolean.err(errorMessage: String): Boolean {
    if (!this) {
        <|> { errorMessage }
    return this
if ((queryParams.size != 2).err("Expect exactly two query params but got ${queryParams.size}")
    || (queryParams["o"] == null).err("Query param o must be populated")
    || (queryParams["p"] == null).err("Query param p must be populated")
) {
    return badRequest().buildAndAwait()
i don't really see a problem with it, personally. The obvious alternative in my mind would be an extension function that throws, instead of logging directly
I mean it seems like basically what you want to do is have a bunch of assertions, no?
you could also go for syntax like this:
Copy code
val assertSuccess = assertScope {
    assert(queryParams["o"] == null, "Query param o must be populated")
    // or as an extension function, doesn't matter
    (queryParams["p"] == null).assert("Query parameter p must be populated")
if (!assertSuccess) {
    return badRequest().buildAndWait()
one thing to note is with your original version you are definitely stuck with short circuiting; here you have the option depending how you write assertScope. You may or may not want that (if multiple conditions are going to fail, you may want to log all of them even if one failing is enough to determine your logic)
that’s a fair point, in my present use case, i definitely rely on short circuiting i’m not quite clear how your proposed
would work though. it would take a block which contained a bunch of asserts, that would each throw if something failed? and then would catch that throw and return a boolean? how would that let me capture all failing asserts?
well, if you want short circuiting, then yes, that's how it would work
if you didn't want short circuiting, then it's actually much simpler
assertScope internally creates an AssertScopeImpl object, that has a boolean field, initialized to true
it has a member function assert which takes a bool and a string, and it ands the boolean with its field, and logs the string if the boolean is false
after running the block with the AssertScopeImpl as a receiver, it returns the boolean field
@Ben Madore I try to understand your example. Isn't it wrong? Shouldn't it be
if (this)
instead of
if (!this)
@Vampire you’re absolutely correct 🙂 that’s what i get for not testing my code before posting it :-D
haha I actually thought that a bit, I stared at it trying to figure out which way th eboolean swere going, then I just assumed you were right and left it