:question: _"How can we guarantee that `@Preview` ...
# compose
d
"How can we guarantee that
@Preview
annotated functions do not end up in production code?"
☝️ This came as a fair challenge from within our team today. I'm working in an environment where adherence to architectural layers, and guaranteed correctness is paramount. As such, it was fairly pointed out that
@Preview
functions strictly belong in a different place to production code. There's an obvious tension there between architectural purity and the practical benefits of placing them alongside `@Composable`'s (such as the intent behind the Code / Split / Design pane). We've arrived at a place where it's deemed acceptable as long as we have a way of guaranteeing that
@Preview
annotated functions cannot accidentally make it into a Release build (either as live or dead code). Do any easily configurable means exist today? If not, could we implement something using the recently released KSP?
e
KSP only adds code
I imagine you could use bytecode transforms (https://developer.android.com/reference/tools/gradle-api/7.0/com/android/build/api/transform/Transform or https://developer.android.com/reference/tools/gradle-api/7.0/com/android/build/api/instrumentation/AsmClassVisitorFactory) to forcibly remove
@Preview
-annotated functions, but that has a possibility of breaking code in the module that happens to use them
r
@darkmoon_uk Do you use R8?
a
Yeah, R8 should strip out all the preview functions as long as they are not referenced by any non-preview code.
👆 4
e
indeed. verifying that may be a bit tricky though. there's -whyareyoukeeping but it doesn't take a specification like "all annotated members"
d
@romainguy I believe so, that being default > AGP 3.4.0, which we are.
r
If it doesn't remove dead code then there's a bug in R8 and you should tell us
d
That's good to know, and was our expectation, that they would be minified out if unreferenced.
r
Using R8 has also other important benefits for Compose like merging lambdas
d
But... and I know this is an edge concern... can we guarantee they aren't accidentally called, to become live code?
r
You could write a custom lint check
Note that there's technically no reason why you couldn't have a production composable that also has a preview annotation
☝️ 2
(without this being a mistake or an architectural issue I mean)
d
Thanks @romainguy, I see how that could be legitimate. We'd like to constrain ourselves in this way though. We are using R8 yes; I'll look into how to write a lint rule that denies invoking
@Preview
annotated functions 👌
👍 5