https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

Ryan Smith

08/10/2022, 12:36 AM
Is there a best practice for when statements where the
else
is there to be exhaustive, but is a
no-op
? e.g.
Copy code
when {
    thing is OneThing -> // do something
    thing is SomethingElse -> // do something else
    else -> { /* no-op */ }
}
It doesn't exactly fit this case from the style guide especially since the app is still under development and there could be more cases:
Prefer using
if
for binary conditions instead of
when
Is a bare
return
better? Or just sticking with
no-op
? Personal preference?
c

Chris Lee

08/10/2022, 1:24 AM
in that specific example it depends on the domain of
thing
- if it is guaranteed to only be
OneThing
or
SomethingElse
, the second conditional can be replaced with the else clause. If the else is required to be exhaustive it should do something - throw an assertion or UnsupportedOperation, perhaps. The no-op else statement is a code-smell.
plus1 4
e

ephemient

08/10/2022, 5:13 AM
stylistically I prefer
Copy code
else -> {} // no-op
but it's really equivalent to what you wrote.
return
isn't always.
t

thanksforallthefish

08/10/2022, 6:03 AM
else -> Unit
is also an option right? because sonar does not like no-op (don’t remember if comments prevent sonar analysis for triggering, but I don’t like “dummy” comments) and
Unit
is the middle ground that makes both me and Sonar not unhappy 😄
c

Chris Lee

08/10/2022, 1:18 PM
if we’re writing a no-op because we believe that code-path can’t be hit, the resilient pattern would be
Copy code
else -> { throw AssertionError("Invalid Thing") }
e

ephemient

08/10/2022, 2:39 PM
error(“invalid")
throws
IllegalStateException
and
TODO("invalid")
throws
NotImplementedError
, which are more specific and appropriate IMO
c

Chris Lee

08/10/2022, 4:56 PM
agreed
r

Ryan Smith

11/01/2022, 2:41 PM
Thank you all for your input! Sorry for replying so late - this thread got absolutely buried in my Slack and I missed all of your excellent feedback at the time