Is there a best practice for when statements where...
# getting-started
r
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
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
stylistically I prefer
Copy code
else -> {} // no-op
but it's really equivalent to what you wrote.
return
isn't always.
t
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
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
error(“invalid")
throws
IllegalStateException
and
TODO("invalid")
throws
NotImplementedError
, which are more specific and appropriate IMO
c
agreed
r
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