We’re having a style discussion on my team and I thought I’d crowd source it. We have a composable w...
j
We’re having a style discussion on my team and I thought I’d crowd source it. We have a composable which is conditionally shown. You can assume this isn’t for a library with a large user base and we don’t have any need to do animation or transitions in this case. Which of these options would you prefer: • A. Encapsulate the conditional display within the composable itself so all consumers get that logic included • B. All consumers should conditionally show/hide the composable by not calling it when they don’t need it • C. Make visibility a parameter for the composable as a compromise between A and B. • D. It depends and none of these are more “right” than the other. See example code in 🧵
Example for option A:
Copy code
@Composable
fun ComponentA(state: SomeStateHolder) {
   if(state.componentAVisible) {
      // Some other composable content
   }
}

@Composable
fun ComponentB(state: SomeStateHolder) {
   // Some composable content
   ComponentA(state)
   // Some composable content
}
Example for Option B:
Copy code
@Composable
fun ComponentA() {
   // Some other composable content
}

@Composable
fun ComponentB(state: SomeStateHolder) {
   // Some composable content
   if(state.componentAVisible) {
       ComponentA(state)
   }
   // Some composable content
}
Example for Option C:
Copy code
@Composable
fun ComponentA(visible: Boolean) {
   if(visible) {
      // Some other composable content
   }
}

@Composable
fun ComponentB(state: SomeStateHolder) {
   // Some composable content
   ComponentA(
      visible = state.componentAVisible
   )
   // Some composable content
}
j
I would go with A specially if feature flags are used
s
I’d consider if ComponentB really needs to know that much about ComponentB. And if ComponentA should even know if it itself should be hidden or not. But I like C the least, and I think I’d opt for B first before I knew more details.
t
Option B is definitely more obvious and you have a clear separation of concerns... Although I wonder if with Option A you get a benefit of having ComponentA's recomp scope come in handy especially if there's dynamic stuff happening inside it... Option A is also easier if you need to read more conditional data from the state for whatever is inside instead of just
componentAVisible
j
We ended up going with Option B in this case. The argument being that the visibility of ComponentA could have ramifications for padding and other layout concerns within the contents of ComponentB so it made sense to keep that external.
m
IMHO Option B is the desired solution. As pointed out by @Tash it maintains clear separation of concerns. I would say any component that is optionally visible on the screen should have that accomplished by the parent that is including it in the layout. Also consider that the visibility affects the layout of ComponentB and thus is the responsibility of ComponentB.