Has anyone made a custom rule/does a default one e...
# detekt
l
Has anyone made a custom rule/does a default one exists that check for
when
statement orders? I’m looking to have all
objects
of a sealed class/interface coming first, then the data classes, so my when(s) would look like:
Copy code
when (a) {
   object1 -> {}
   object2 -> {}
   object3 -> {}
   is dc1 -> {}
   is dc2 -> {}
}
And not with
is
mixed between all the statements
c
branches in a when expression are evaluated in the order provided; would be questionable to force an arbitrary order that may not align with the logic of the expression.
l
Can you explain better? The page says
matches its argument against all branches sequentially until some branch condition is satisfied.
Meaning that it try from the first until there’s a match, then stops, right?
c
that’s correct.
l
If I have a
sealed interface
with
3 objects
and
2 data classes
my instance will be either an object (only one), or a data class
I don’t see a problem in having some code order there 🤷🏼, trying to match object firsts, and then data classes
c
yes, but it can satisfy any number of conditions. For example, if classes implement several interfaces (A, B, C) you may have logic where
is C
is checked before
is A
. Also, performance may be a consideration - will often organize when expressions knowing that certain conditions are frequently hit (or not).
l
We don’t have that structure for now, so, do you know if there is a way or not?
c
No idea if there is a way. Suggesting it won’t be common or prudent for the reasons above.
l
Thanks 🙂
b
That's completely doable but as far as I know there's nothing like that implemented.
In general I prefer to group the when in a logical order. First loading state, the errors and then success. Or something similar. The problem is that a rule is difficult to umpteenth to do something like that. Is the same as keep the related functions together.
l
Any suggestions/hints on how to get started with that?
b
Use this template https://github.com/detekt/detekt-custom-rule-template and look at detekt for a rule that does something similar. In your case a rule related with
when
. Copy&paste that rule to your project and edit it until it does what you want.
In general is a really good idea to write the test first.
And I'm not a tdd fan. Tests first works really well with detekt