Hi all. What is naming convention applies for nami...
# naming
x
Hi all. What is naming convention applies for naming preview constants in #CJLTWPH7S?
Copy code
private val previewState = State()
// or
private val PreviewState = State()
According to coding convention,
Names of top-level or object properties which hold objects with behavior or mutable data should use camel case names:
Copy code
val mutableCollection: MutableSet<String> = HashSet()
Names of properties holding references to singleton objects can use the same naming style as
object
declarations:
Copy code
val PersonComparator: Comparator<Person> = /*...*/
For context - this is to be used in, for example
Copy code
@Composable 
fun Screen(state: State)

@Preview
@Composable 
fun ScreenPreview() { 
  Screen(state = PreviewState) 
}
tumbleweed 1
m
I've never run into this particular situation because I tend to make that kind of state local within the preview function (to avoid allocating it at runtime), or if I need to reuse the same state in many places, I use a factory function (which is also convenient because I often need to customize a few things about the state for different kinds of previews, so I can add parameters to the factory function). In any case, I don't see why it being involved in preview should affect the capitalization convention. I would consider it like you would consider any global variable. In this kind of situation, I usually think about it like this: At the point-of-use, does the naming convention communicate useful information? I'm assuming that this isn't actually a Compose State, but your own class? (If it's a Compose State, it should definitely be lowerCamelCase). So to avoid confusion, I'll call it
ScreenState
to avoid ambiguity with the built-in
State
type. So... if
ScreenState
is an immutable data class, then it would make perfect sense to use UpperCamelCase like a singleton object. But if it were me, I'd probably make it a property on the companion object to avoid cluttering up the global namespace, and make it lazy to avoid allocating it when there's no preview:
Copy code
data class ScreenState(.......etc...) {
    companion object {
        val PreviewState by Lazy { ScreenState() }
    }
}
On the other hand, if
ScreenState
is mutable members, for example:
Copy code
class ScreenState {
    val something by mutableStateOf(......)
}
....then I would definitely not consider it a singleton, and I would lean away from using a share global var (because it could be mutated) and towards a factory function instead, like:
Copy code
class ScreenState {
    val something by mutableStateOf(......)
    companion object {
        fun makePreviewState(.....) = ScreenState(.....)
    }
}
Hope that helps! Also... #C0474L1Q8DR feels a bit dead these days, which is sad because I really like the idea.tumbleweed
👀 1